我已经阅读了几个如何使用动态sql返回输出参数的示例,但所有这些都略有不同,因为它们在过程中创建了变量,而不是传入它们(我假设这是根的我的问题)。我收到错误:
Must declare the table variable "@tbl".
当我尝试运行下面的过程时(在执行它的测试代码之后列出)。我接近了吗?
DECLARE @tbl nvarchar(40)
DECLARE @bnch INT
SET @tbl = 'tblDailyPricingAndVol'
EXEC sprocReturnDataPointBenchmark @tbl, @bnch
存储过程:
ALTER PROCEDURE [dbo].[sprocReturnDataPointBenchmark] @tblName NVARCHAR(50),
@benchmark BIGINT OUTPUT
AS
BEGIN
DECLARE @sql nvarchar(1000),
@parameters NVARCHAR(100) = N'@tbl NVARCHAR(50), @benchOUT BIGINT OUTPUT';
SET @sql = N'SELECT @benchOUT = Count(ID) FROM @tbl WHERE DateAdded = ' +
'(SELECT MAX(DateAdded) FROM tblDailyATR AS T2)';
EXEC sp_executesql @sql, @parameters, @tbl = @tblName, @benchOUT = @benchmark OUTPUT
SELECT @benchmark
END
答案 0 :(得分:1)
上面列出的第一个传递中有几个语法错误,但我需要解决的概念问题是尝试在动态sql中的参数变量中传递表名(输入参数)。这里的好例子是:Generate dynamic SQL statements in SQL Server
所以,我修改后的工作代码是:
ALTER PROCEDURE [dbo].[sprocReturnDataPointBenchmark] @tblName NVARCHAR(50),
@benchmark BIGINT OUTPUT
AS
BEGIN
DECLARE @sqlStatement nvarchar(500)
DECLARE @parameters NVARCHAR(100)
DECLARE @fullStatement NVARCHAR(500)
SET @parameters = '@benchmark BIGINT OUTPUT'
SET @sqlStatement = N'SELECT @benchmark = Count(ID) FROM ' + @tblName + ' WHERE DateAdded = ' +
'(SELECT MAX(T2.DateAdded) FROM ' + @tblName + ' AS T2)';
EXEC sp_executesql @sqlStatement, @parameters, @benchmark = @benchmark OUTPUT
SELECT @benchmark
END