SQL 通过syscolumns.xtype动态查找指定数据类型字段所包含的数据

表中太多列,只想查找某些比如,数据类型为varchar的字段的数据。

  思路:1、先获取列名:

select * from syscolumns 
where id=(select max(id) from sysobjects where xtype='u' and name='test_A')

  

  2、查找指定数据类型,xtype就是数据类型,参考如下

syscolumns表内的xtype

  查了一下,这些东西都是存于每一个数据库的syscolumns表里面得,name就是列名,xtype就是数据类型,但是这个xtype是数字的,下面是数字和数据类型对应的关系;

 xtype=34 'image' 
 xtype= 35 'text' 
 xtype=36 'uniqueidentifier' 
 xtype=48 'tinyint' 
 xtype=52 'smallint' 
 xtype=56 'int' 
 xtype=58 'smalldatetime' 
 xtype=59 'real' 
 xtype=60 'money' 
 xtype=61 'datetime' 
 xtype=62 'float' 
 xtype=98 'sql_variant' 
 xtype=99 'ntext' 
 xtype=104 'bit' 
 xtype=106 'decimal' 
 xtype=108 'numeric' 
 xtype=122 'smallmoney' 
 xtype=127 'bigint' 
 xtype=165 'varbinary' 
 xtype=167 'varchar'

 xtype=173 'binary' 
 xtype=175 'char' 
 xtype=189 'timestamp' 
 xtype=231 'nvarchar'

 xtype=239 'nchar' 
 xtype=241 'xml' 
 xtype=231 'sysname'

3、构造最终的动态SQL语句:

DECLARE @sql VARCHAR(max)
DECLARE @col VARCHAR(1000)

SELECT @col = STUFF((SELECT ','+name FROM syscolumns where id=(select max(id) from sysobjects where xtype='u' and name='test_A')
AND sys.syscolumns.xtype= 167 for xml path('')),1,1,'')

SET @sql='select '+@col
SET @sql=@sql+' from test_A'
EXEC(@sql)

 

posted @ 2016-08-31 10:59  山治先生  阅读(1610)  评论(0编辑  收藏  举报