1

我在我的 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。感谢您的帮助。

4

1 回答 1

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
于 2012-06-18T12:23:20.057 回答