类似于T-SQL中变量的数组访问

Dmi*_*nov 9 t-sql

在我的存储过程中,我有多个类似的变量@V1,@V2... @V20(假设其中20个)来自记录的FETCHED.我如何使用动态SQL使用这些变量作为参数对另一个存储过程进行20次调用?

当然@V[i]语法不正确,但它表达了意图

    fetch next from maincursor into @status, @V1, @V2, ...

    while @i<21
    begin
       -- ??? execute sp_executesql 'SecondSP', '@myParam int', @myParam=@V[i]
       -- or 
       -- ??? execute SecondSP @V[i]
       set @i = @i+1
    end
Run Code Online (Sandbox Code Playgroud)

Jon*_*son 18

正如其他人所说,设置一个临时表,将所需的值插入其中.然后"迭代"通过它从这些值执行必要的SQL.这将允许您执行0到MANY值,因此您不必为每个值设置变量.

以下是一个完整的示例,说明如何在没有游标的情况下执行此操作.

SET NOCOUNT ON

DECLARE @dict TABLE (
                    id          INT IDENTITY(1,1), -- a unique identity column for reference later
                    value       VARCHAR(50),       -- your parameter value to be passed into the procedure
                    executed    BIT                -- BIT to mark a record as being executed later
                    )

-- INSERT YOUR VALUES INTO @dict HERE
-- Set executed to 0 (so that the execution process will pick it up later)
-- This may be a SELECT statement into another table in your database to load the values into @dict
INSERT @dict
SELECT 'V1Value', 0 UNION ALL
SELECT 'V2Value', 0

DECLARE @currentid INT
DECLARE @currentvalue VARCHAR(50)
WHILE EXISTS(SELECT * FROM @dict WHERE executed = 0)
BEGIN
    -- Get the next record to execute
    SELECT 
    TOP 1   @currentid = id 
    FROM    @dict 
    WHERE   executed = 0

    -- Get the parameter value
    SELECT  @currentvalue = value
    FROM    @dict
    WHERE   id = @currentid

    -- EXECUTE THE SQL HERE
    --sp_executesql 'SecondSP', '@myParam int', @myParam = 
    PRINT   'SecondSP ' +  '@myParam int ' + '@myParam = ' + @currentvalue

    -- Mark record as having been executed
    UPDATE  d
    SET     executed = 1
    FROM    @dict d
    WHERE   id = @currentid
END
Run Code Online (Sandbox Code Playgroud)


Jam*_*ack 0

为什么不直接使用表变量,然后循环遍历表获取每个值。

基本上将表格中的每一行视为数组单元格,表格只有一列。

只是一个想法。:)