SQL语句编译的时候没有问题,执行时出错,请问怎么回事?
drop table t1create table t1(id varchar(10),cusno varchar(10),price numeric(10,2))insert t1 select 'S012','A',35.02union allselect 'S012','C',38.60union all select 'S013','A',52.00Declare @S Varchar(8000) Select @S='Select ID,'Select @S=@S + 'SUM(Case Cusno When '''+ Cusno+ ''' Then Price Else 0.00 End) As Price' + Cusno From t1 Group By Cusno Select @S = @S + ' From t1 Group By ID 'EXEC(@S) GO
drop table t1create table t1(id varchar(10),cusno varchar(10),price numeric(10,2))insert t1 select 'S012','A',35.02union allselect 'S012','C',38.60union all select 'S013','A',52.00Declare @S Varchar(8000) Select @S='Select ID'Select @S=@S + ',SUM(Case Cusno When '''+ Cusno+ ''' Then Price Else 0.00 End) As Price' + Cusno From t1 Group By Cusno Select @S = @S + ' From t1 Group By ID 'exec(@S) GO /*ID PriceA PriceC ---------- ---------------------------------------- ---------------------------------------- S012 35.02 38.60S013 52.00 .00*/
[解决办法]
declare @s varchar(8000)
set @s='select id'
select @s=@s +',sum(case cusno when '''+cusno+''' then price else 0.00 end) as price'+cusno
from t1 group by cusno
select @s=@s+' from t1 group by id'
exec (@s)