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

SQL语句编译的时候没有问题,执行时出错,请问怎么回事?
SQL code
drop table t1
create table t1(id varchar(10),cusno varchar(10),price numeric(10,2))
insert t1 
select 'S012','A',35.02
union all
select 'S012','C',38.60
union all 
select 'S013','A',52.00





Declare   @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 


在查询分析器中,能编译,执行报错
“服务器: 消息 156,级别 15,状态 1,行 1
在关键字 'Case' 附近有语法错误。”
请问错在哪里?
谢谢!


------解决方案--------------------
SQL code
drop table t1
create table t1(id varchar(10),cusno varchar(10),price numeric(10,2))
insert t1 
select 'S012','A',35.02
union all
select 'S012','C',38.60
union all 
select 'S013','A',52.00





Declare   @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.60
S013       52.00                                    .00


*/

------解决方案--------------------
SQL code
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)


1\select @s=@s+ ' from t1 group by id ' 在from 前加一个空格


2\另个select @s=@s + ',sum(case cusno when ' ' '+cusno+ ' ' ' then price else 0.00 end) as price '+cusno 

as price 后的空格去掉