select file,'a' name,a num from t where a<>0
union all
select file,'b' name,b num from t where b<>0
union all
select file,'c' name,c num from t where c<>0
union all
select file,'d' name,d num from t where d<>0
union all
select file,'b' name,b num from t where b<>0
union all
select file,'c' name,c num from t where c<>0
union all
select file,'d' name,d num from t where d<>0
declare @s1 varchar(8000),@s2 varchar(8000)
,@s3 varchar(8000),@s4 varchar(8000),@s5 varchar(8000)
,@i varchar(10)
select @s1='',@s2='',@s3='',@s4='',@s5='',@i='0'
select @s1=@s1+',@'+@i+' varchar(8000)'
,@s2=@s2+',@'+@i+'=''select [file],name='''''+name+''''',num=['+name+'] from 表 where ['+name+']<>0'''
,@s3=@s3+'+'' union all ''+@'+@i
,@i=cast(@i as int)+1
from syscolumns
where object_id('表')=id and name<>'file'select @s1=substring(@s1,2,8000)
,@s2=substring(@s2,2,8000)
,@s3=substring(@s3,16,8000)exec('declare '+@s1+'
select '+@s2+'
exec(''select * from(''+'+@s3+'+'')a order by [file],name'')')
--测试数据
create table 表([file] char(2),a int,b int,c int,d int)
insert 表 select 'f1',0,1,2,0
union all select 'f2',2,4,0,3
go--查询处理
declare @s1 varchar(8000),@s2 varchar(8000)
,@s3 varchar(8000),@s4 varchar(8000),@s5 varchar(8000)
,@i varchar(10)
select @s1='',@s2='',@s3='',@s4='',@s5='',@i='0'
select @s1=@s1+',@'+@i+' varchar(8000)'
,@s2=@s2+',@'+@i+'=''select [file],name='''''+name+''''',num=['+name+'] from 表 where ['+name+']<>0'''
,@s3=@s3+'+'' union all ''+@'+@i
,@i=cast(@i as int)+1
from syscolumns
where object_id('表')=id and name<>'file'select @s1=substring(@s1,2,8000)
,@s2=substring(@s2,2,8000)
,@s3=substring(@s3,16,8000)exec('declare '+@s1+'
select '+@s2+'
exec(''select * from(''+'+@s3+'+'')a order by [file],name'')')
go
--删除测试
drop table 表/*--测试结果file name num
---- ---- -----------
f1 b 1
f1 c 2
f2 a 2
f2 b 4
f2 d 3(所影响的行数为 5 行)--*/
我是这样的insert into table2 select file,'a' as name,a where a<>0
可是要很多啊,我的意思是‘a'能否用变量代替