日期:2014-05-19  浏览次数:20391 次

刚才提问出了点错,sql数据库字段求和
表如下:
        name   a     b     c      
            w     1     1     1    
            x     2     2     2    
            y     3     3     3  
 
谁能告诉我求a,b,c三个字段分别求合计    
即查询结果为:    
        name   a     b     c    
        null   6     6     6
要动态的,因为我的数据库字段是动态的,字段不一定。
注意以上表为整个一张表,前面包括一个char字段。
查询结果也应该包含name字段,但是值为空
谢谢帮忙!


------解决方案--------------------
--创建测试环境
drop table tbtest
go
create table tbtest(name varchar(10),a int,b int,c int)
insert into tbtest(a,b,c)
select 1,1,1
union all select 2,2,2
union all select 3,3,3

--查询
declare @s varchar(1000)
set @s= ' '
select @s=@s+ ',sum( '+name+ ') as ' ' '+name+ ' ' ' ' from syscolumns where id=object_id( 'tbtest ') and xtype in (127,104,106,62,56,60,108,52,122)
exec( 'select name=null '+@s+ ' from tbtest ')
/*
name a b c
----------- ----------- ----------- -----------
NULL 6 6 6
*/