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

关于SQL中变量的问题
存储过程如下:
create proc uspFillQuestion  
  @Top int,
  @Question_Subject varchar (100),
  @Question_Chapter varchar (100)
   
AS
  DECLARE @sql varchar (100)
  SET @sql = 'SElECT TOP '+ cast(@Top as varchar(10))+'* from Fill_Question where Question_Subject=@Question_Subject and Question_Chapter=@Question_Chapter order by newid()'
  EXEC(@sql)
SQLhelper如下
SQLhelper helper = new SQLhelper();
SqlParameter[] param =
  {
  new SqlParameter("@Top",SqlDbType.Int),
  new SqlParameter("@Question_Subject",SqlDbType.VarChar,100),
  new SqlParameter("@Question_Chapter",SqlDbType.VarChar,100)
  ) ;
param[0].Value = Fill.Top;
param[1].Value = Fill.Fill_Subject;
param[2].Value = Fill.Fill_Chapter;

return helper.ExecuteDataSet("uspGetFillQuestion",param);

实在是搞不明白了。不知道在哪里出现了问题!!!!
给出的错误提示是 "必须声明标量变量@Question_Subject"

------解决方案--------------------
主要是这里出了问题:
SET @sql = 'SElECT TOP '+ cast(@Top as varchar(10))+'* from Fill_Question where Question_Subject=@Question_Subject and Question_Chapter=@Question_Chapter order by newid()' 
你这里是动态执行sql,但是注意红色部分你是写在单引号内的,即使动态sql是这样的SElECT TOP xxx * from Fill_Question where Question_Subject=@Question_Subject and Question_Chapter=@Question_Chapter order by newid()
在这段sql里你并没有申明@Question_Subject 和@Question_Chapter