读书人

请大家帮找找这个SQL语句的错解决办法

发布时间: 2012-02-17 17:50:42 作者: rapoo

请大家帮找找这个SQL语句的错
declare @num int,@sql varchar(1000),@chengjibiao varchar(10),@classid int
select @num=count(*) from examsubject where gradeid=1 and examlistid=3083
select @chengjibiao=convert(varchar(10),考试时间,112) from examlist where examlistid=3083
set @sql= 'select studentid as 学号,(select 姓名 from student where studentid=[ '+@chengjibiao+ '].studentid) as 姓名,语文,数学,英语,物理,化学,生物,地理,历史,政治,(语文+数学+英语+物理+化学+生物+地理+历史+政治) as 总分,convert(decimal(4, 1),(语文+数学+英语+物理+化学+生物+地理+历史+政治)/@num) as 平均分 from [ '+@chengjibiao+ '] where gradeid=1 '
exec (@sql)


消息 137,级别 15,状态 2,第 1 行
必须声明标量变量 "@num "。


[解决办法]
@num 是变量,怎么能直接写在 @SQL中呢? 应该是


set @sql= 'select studentid as 学号,(select 姓名 from student where studentid=[ '+@chengjibiao+ '].studentid) as 姓名,语文,数学,英语,物理,化学,生物,地理,历史,政治,(语文+数学+英语+物理+化学+生物+地理+历史+政治) as 总分,convert(decimal(4, 1),(语文+数学+英语+物理+化学+生物+地理+历史+政治)/ '+str(@num)+ ') as 平均分 from [ '+@chengjibiao+ '] where gradeid=1 '

@num是整型,所以要转换成字符型

读书人网 >SQL Server

热点推荐