我已经声明并设置了一些变量。然后我想在执行存储过程时使用该变量值作为参数。但我总是得到错误
必须声明标量变量。
以下是我的变数:
--declare variables for parameter @listweek
declare @tgl_other varchar(50);
--set variables for parameter @listweekset
set @tgl_other = (select top 1 ltrim(rtrim(cast(numweek as char)))+'-('+rangeweek+')' from tbl_weeklyflash where year(dates) = year(getdate()) order by numweek desc);
--the variable values should be like this 30-(01-03-2012 - 08-03-2012)
--and this value that I want to use as parameter value in executing stored procedure
这是执行存储过程:
insert into my_table (field1, field2, field3)
EXEC my_store_procedure @tgl_other
-- the parameter for my_store_procedure is like '30-(01-03-2012 - 08-03-2012)'
我的变量不正确吗?或者我错误地使用变量参数?
更新:
如果我执行此查询:
declare @tgl_other varchar(50);
set @tgl_other = (select top 1 ltrim(rtrim(cast(numweek as char)))+'-('+rangeweek+')' from tbl_weeklyflash where year(dates) = year(getdate()) order by numweek desc);
EXEC my_store_procedure @tgl_other
它工作正常,但如果我添加INSERT INTO..
语句,它将无法正常工作。为什么会这样?
更新II:
这是我尝试运行的整个查询
declare @tgl_other varchar(50);
set @tgl_other = (select top 1 ltrim(rtrim(cast(numweek as char)))+'-('+rangeweek+')' from tbl_weeklyflash where year(dates) = year(getdate()) order by numweek desc);
TRUNCATE TABLE mytable
GO
INSERT INTO mytable (field1, field2)
EXEC my_store_procedure @tgl_other
GO
答案 0 :(得分:5)
在声明变量和执行存储过程的调用之间是否有GO
?变量只在其范围内可见 - 当你在其中有一个GO时,它会终止前一个批次/范围并开始一个新的 - 并且在那个新的变量中,变量不再可见/声明了。
所以试试这个:
declare @tgl_other varchar(50);
set @tgl_other = (select top 1 ltrim(rtrim(cast(numweek as char)))+'-('+rangeweek+')' from tbl_weeklyflash where year(dates) = year(getdate()) order by numweek desc);
TRUNCATE TABLE mytable
-- GO remove this GO to make it work!
INSERT INTO mytable (field1, field2)
EXEC my_store_procedure @tgl_other
GO