How can one iterate over stored procedure results from within another stored procedure…without cursors?

前端 未结 7 1847
半阙折子戏
半阙折子戏 2020-12-19 07:06

I\'m not sure if this is something I should do in T-SQL or not, and I\'m pretty sure using the word \'iterate\' was wrong in this context, since you should never iterate any

相关标签:
7条回答
  • 2020-12-19 08:12

    You can use a temp table or table variable with an additional column:

    DECLARE @MyTable TABLE (
        Column1 uniqueidentifer,
        ...,
        Checked bit
    )
    
    INSERT INTO @MyTable
    SELECT [...], 0 FROM MyTable WHERE [...]
    
    DECLARE @Continue bit
    SET @Continue = 1
    WHILE (@Continue)
    BEGIN
        SELECT @var1 = Column1,
               @var2 = Column2,
               ...
        FROM @MyTable
        WHERE Checked = 1
    
        IF @var1 IS NULL
            SET @Continue = 0
        ELSE
        BEGIN
    
            ...
    
            UPDATE @MyTable SET Checked = 1 WHERE Column1 = @var1
        END
    END
    

    Edit: Actually, in your situation a join will be better; the code above is a cursorless iteration, which is overkill for your situation.

    0 讨论(0)
提交回复
热议问题