表中太多列,只想查找某些比如,數據類型為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)
?