0

I have a table that will return an Integer. Many times the below query will return multiple IDs.

DECLARE @ID INT;

SELECT @ID = Id
        FROM MyTable

I then have to execute a pre made stored procedure that accepts that Id. The Stored Procedure is setup to take one Id at a time (I can't change it to make a list). How can I get the stored procedure to iterate over the entire list of IDs Returned?

exec storedProc @ID
9
  • Which dbms are you using? The above code won't work on most products. Commented Sep 21, 2023 at 12:10
  • @Jarlh Microsoft SSMS Commented Sep 21, 2023 at 12:12
  • 1
    @Dev101684 Consider, by analogy, that jarlh just asked you what model of car you drive, and you just responded with "unleaded gasoline". Commented Sep 21, 2023 at 12:15
  • @jarlh my apologies if i misunderstood, its a relational database using Microsoft SQL Server, thanks for your willingness to to help! Commented Sep 21, 2023 at 12:24
  • 1
    If you cannot change your procedure you will have to execute it for each ID in a loop, aka cursor. Commented Sep 21, 2023 at 12:25

1 Answer 1

0

You can try following

Add new column 'Processed' tinyint with default value as zero on your table, to hold processed flag (assume: 0 - New, 1 - Successfully processed, 2 - Error ). Iterate each unprocessed records where Processed=0 (new), get ID value and execute the stored procedure by passing the ID. After the execution of stored procedure, update processed as 1. If any error, set processed = 2.


DECLARE @ID INT;
SELECT TOP 1 @ID = Id  FROM MyTable
WHERE Processed = 0
    
WHILE @@ROWCOUNT<>0
BEGIN
    BEGIN TRY

        EXEC storedProc @ID

        UPDATE MyTable SET Processed = 1 
        WHERE ID = @ID
                    
    END TRY
    BEGIN CATCH
        SELECT @ID ID, ERROR_MESSAGE() as ErrMsg
        
        UPDATE MyTable SET Processed = 2 -- Error 
        WHERE ID = @ID
    END CATCH

-- Get Next record
SELECT TOP 1 @ID = Id  FROM MyTable
WHERE Processed = 0

End  -- While..end
Sign up to request clarification or add additional context in comments.

Comments

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.