首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

SQL语句编译的时候没有有关问题,执行时出错,请教咋回事

2012-02-02 
SQL语句编译的时候没有问题,执行时出错,请问怎么回事?SQL codedrop table t1create table t1(id varchar(1

SQL语句编译的时候没有问题,执行时出错,请问怎么回事?

SQL code
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 


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


[解决办法]
SQL code
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*/
[解决办法]
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 后的空格去掉

热点排行