Search code examples
sqlt-sqlstored-procedures

Run stored procedure for each row of a table


I have a table that look something like this

value_1  value_2  value_3
---------------------------
   1        2        3
   4        5        6
   7        8        9
   ...     ...     ...

and I need to run a stored procedure for every row of this table, something like

foreach value_1, value_2, value_3 from my_table
exec spProcedure value_1, value_2, value_3

Is there a way to do this?


Solution

  • You can use a cursor:

    DECLARE @value1 INT,
            @value2 INT,
            @value3 INT 
    
    DECLARE cursorElement CURSOR FOR
                SELECT  value_1, value_2, value_2
                FROM    table
    
    
    OPEN cursorElement
    FETCH NEXT FROM cursorElement INTO @value1, @value2, @value3
    
    WHILE ( @@FETCH_STATUS = 0 )
    BEGIN
        exec spProcedure @value1, @value2, @value3
    
        FETCH NEXT FROM cursorElement INTO @value1, @value2, @value3
    END         
    CLOSE cursorElement
    DEALLOCATE cursorElement