原因:sx数据类型是char或者nchar,不是varchar或者nvarchar
declare @s varchar(800)
set @s='Select sid'
select @s=@s+', ['+rtrim(sx)+']=sum(case when sx='''+rtrim(sx)+''' then smoney else 0 end )'
from BB
group by rtrim(sx)
select @s

解决方案 »

  1.   

    declare @s varchar(800)
    set @s='Select sid'
    select @s=@s+', sum(case sx when '''+sx+''' then smoney else 0 end )[' + sx+ ']'
    from (select distinct sx from bb) as a
    set @s = @s+ ' from bb group by sid'
    select @s
      

  2.   

    declare @s varchar(800)
    set @s='Select sid'
    select @s=@s+', sum(case sx when '''+cast(sx varchar)+''' then smoney else 0 end )[' + sx+ ']'
    from (select distinct sx from bb) as a
    set @s = @s+ ' from bb group by sid'
    select @s
      

  3.   

    to Haiwer(海阔天空) 和 dawugui(潇洒老乌龟)
     谢谢你们
     然而,我是想问该SQL语句如何产生这样的结果! 而不是说结果不正确,只是不理解执行这语句后,SQL是如何执行的,然后产生如上结果..
      

  4.   

    print @S 与 select @S 结果如下:
    Select sid, [a ]=sum(case when sx='a ' then smoney else 0 end ),
    [b ]=sum(case when sx='b ' then smoney else 0 end ),
    [c ]=sum(case when sx='c ' then smoney else 0 end )为什么是这样子的结果了??