1

我已经声明并设置了一些变量。然后我想将该变量值用作执行存储过程的参数。但我总是出错

必须声明标量变量。

这是我的变量:

--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..语句它将不起作用。为什么会发生?


更新二:这是我尝试运行的整个查询

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
4

1 回答 1

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
于 2012-07-31T07:16:35.683 回答