带有多个参数的参数化sql

时间:2012-06-18 12:19:41

标签: sql dynamic parameterized

我在SQL查询中遗漏了一些东西,可以请有人建议如何纠正它吗?这是我的SQL:

declare @numItems int;
declare @value1 int;
declare @value2 int;
declare @currentValue int;
declare @counter int;
declare @qry nvarchar(max)

set @value1 = 5;
set @value2 = 10;

set @numItems = 2
set @counter=0

WHILE (@counter < @numItems)
BEGIN
    set @qry = 'set @currentValue = @value' + cast(@counter+1 as nvarchar(max)) + ';'   
    exec sp_executesql @qry, N'@currentValue int OUTPUT', @currentValue OUTPUT

    print @currentValue

    set @counter = @counter + 1;
END

我想要的是@currentValue参数获取@ value1和@ value2的值并打印它们。 我不确定如何在exec语句中正确声明参数。我正在使用SQL Server 2005.感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

declare @numItems int;
declare @value1 int;
declare @value2 int;
declare @currentValue int;
declare @counter int;
declare @qry nvarchar(max)

set @value1 = 5;
set @value2 = 10;

set @numItems = 2
set @counter=0

WHILE (@counter < @numItems)
BEGIN
    set @qry = 'set @currentValue = @value' + cast(@counter+1 as nvarchar(max)) + ';'   
    exec sp_executesql @qry, 
                        N'@value1 int, @value2 int, @currentValue int OUTPUT', 
                        @value1=@value1,@value2=@value2, @currentValue = @currentValue OUTPUT

    print @currentValue

    set @counter = @counter + 1;
END