How can I iterate over a recordset within a stored procedure?

后端 未结 3 693
醉梦人生
醉梦人生 2021-02-02 12:33

I need to iterate over a recordset from a stored procedure and execute another stored procedure using each fields as arguments. I can\'t complete this iteration in the code. I h

3条回答
  •  萌比男神i
    2021-02-02 13:11

    try this (cursor free looping):

    CREATE TABLE #Results  (RowID  int identity(1,1), Col1  varchar(5), Col2 int, ... )
    DECLARE @Current  int
           ,@End      int
    DECLARE @Col1  varchar(5)
           ,@Col2 int
           ,...
    
    --you need to capture the result set from the primary stored procedure
    INSERT INTO #Results
        (Col1, COl2,...)
        EXEC nameofstoredprocedure_1 arg1, arg2, arg3
    SELECT @End=@@ROWCOUNT,@Current=0
    
    --process each row in the result set
    WHILE @Current<@End
    BEGIN
        SET @Current=@Current+1
    
        SELECT
            @Col1=COl1, @Col2=Col2
            FROM #Results
            WHERE RowID=@Current
    
        --call the secondary procedure for each row
        EXEC nameofstoredprocedure_2  @Col1, @Col2,...
    
    END
    

    working example:

    CREATE PROCEDURE nameofstoredprocedure_1
    (@arg1 int, @arg2 int, @arg3 int)
    AS
    SELECT 'AAA',@arg1 UNION SELECT 'BBB',@arg2 UNION SELECT 'CCC',@arg3
    GO
    
    CREATE PROCEDURE nameofstoredprocedure_2
    (@P1 varchar(5), @P2 int)
    AS
    PRINT '>>'+ISNULL(@P1,'')+','+ISNULL(CONVERT(varchar(10),@P2),'')
    GO
    
    CREATE TABLE #Results  (RowID  int identity(1,1), Col1  varchar(5), Col2 int)
    DECLARE @Current  int
           ,@End      int
    DECLARE @Col1  varchar(5)
           ,@Col2 int
    
    
    INSERT INTO #Results
        (Col1, COl2)
        EXEC nameofstoredprocedure_1 111, 222, 333
    SELECT @End=@@ROWCOUNT,@Current=0
    
    WHILE @Current<@End
    BEGIN
        SET @Current=@Current+1
    
        SELECT
            @Col1=COl1, @Col2=Col2
            FROM #Results
            WHERE RowID=@Current
    
        EXEC nameofstoredprocedure_2  @Col1, @Col2
    
    END
    

    OUTPUT:

    (3 row(s) affected)
    >>AAA,111
    >>BBB,222
    >>CCC,333
    

提交回复
热议问题