1

Is it possible to execute a stored procedure for each row in a SELECT? This only executes the first row, looking for something to execute for all rows:

    Declare 
        @Loop bit = 1, @ID int, @Exists bit, @ReturnValue bit = 0

    WHILE (@Loop) = 1
        BEGIN

            SELECT @ID = ID FROM Table --Multiple Rows Returned

            EXEC [dbo].[StoredProc1] --Exec SP for Each Row
                @InputID = @ID
                ,@Exists = @Exists OUTPUT

            IF @Exists = 1 
                 BEGIN
                     SET @Loop = 0
                     SET @ReturnValue = 1
                 END

        END

    SELECT @ReturnValue [ReturnValue]

1 Answer 1

6

Use a cursor:

DECLARE @exists     bit
DECLARE db_cursor   CURSOR FOR  
SELECT  ID 
FROM    Table

OPEN    db_cursor   
FETCH NEXT FROM db_cursor INTO @ID   

WHILE @@FETCH_STATUS = 0   
BEGIN   
       EXEC [dbo].[StoredProc1] --Exec SP for Each Row
            @ID
            , @exists OUTPUT  

       FETCH NEXT FROM db_cursor INTO @id   
END   

CLOSE db_cursor   
DEALLOCATE db_cursor
Sign up to request clarification or add additional context in comments.

6 Comments

Strongly recommend adding LOCAL STATIC READ_ONLY FORWARD_ONLY to the cursor declaration.
@AaronBertrand: If you're going to recommend a bunch of voodoo like that, you should specify why -- otherwise it just encourages cargo cult programming. I certainly have no idea why you'd bother to specify READ_ONLY FORWARD_ONLY on a STATIC cursor, and using STATIC can have pretty serious repercussions if you use it wrong. Is there any need for LOCAL on a cursor that gets deallocated when it's closed, like in the given code?
@Gabe I've since written this post, and it is not a "bunch of voodoo": sqlperformance.com/2012/09/t-sql-queries/cursor-options However, based on code I still see every day, I'm not too concerned that my passing comment is going to flip the industry upside down.
@AaronBertrand: I'm afraid your post wasn't very enlightening. It appears to recommend FAST_FORWARD, and doesn't show a meaningful effect from adding READ_ONLY FORWARD_ONLY.
@Gabe did you read the whole post, e.g. the part where I mention that I used to recommend LOCAL STATIC READ_ONLY FORWARD_ONLY? Sorry I didn't go back in time and change every comment I've made about this all over the web.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.