日期:2014-05-18  浏览次数:20537 次

有一句需要大家给予解释一下

declare   @sql   varchar(8000)
set   @sql   =   'select   xh '
select   @sql   =   @sql   +   '   ,   sum(case   kc   when   ' ' '   +   kc   +   ' ' '   then   cj   else   0   end)   [ '   +   kc   +   '] '
from   (select   distinct   kc   from   t)   as   a
set   @sql   =   @sql   +   '   from   t   group   by   xh '
exec(@sql)  


------解决方案--------------------
declare @sql varchar(8000)
set @sql = 'select xh '
select @sql = @sql + ' , sum(case kc when ' ' ' + kc + ' ' ' then cj else 0 end) [ ' + kc + '] '
from (select distinct kc from t) as a
set @sql = @sql + ' from t group by xh '


print @sql --打印出来SQL语句

exec(@sql)


exec 是系统提供的可以执行一个串。
------解决方案--------------------
先改成
declare @sql varchar(8000)
set @sql = 'select xh '
select @sql = @sql + ' , sum(case kc when ' ' ' + kc + ' ' ' then cj else 0 end) [ ' + kc + '] '
from (select distinct kc from t) as a
set @sql = @sql + ' from t group by xh '
print @sql

执行,
再改成
declare @sql varchar(8000)
set @sql = 'select xh '
select @sql = @sql + ' , sum(case kc when ' ' ' + kc + ' ' ' then cj else 0 end) [ ' + kc + '] '
from (select distinct kc from t) as a
print @sql
执行
我想你就基本明白了