Run stored procedure for each row of a table
Asked Answered
L

3

5

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?

Leisure answered 11/6, 2014 at 7:27 Comment(3)
from another stored procedure or in a program?Garretgarreth
just an sql query to run in SQL Management studioCherimoya
Possible duplicate of SQL - Call Stored Procedure for each recordIndisputable
G
13

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
Garretgarreth answered 11/6, 2014 at 7:37 Comment(0)
D
0
DECLARE @Query varchar(MAX);  
select @Query=STUFF((SELECT 'EXEC dbo.spProcedure @value1=' +QUOTENAME(clm1,'''') 
       + ';' from dbo.my_table
FOR XML PATH('')),1,0,'');
EXEC(@Query);

If you do not want to make any changes to the passing values and pass all the table values in bulk

Dismember answered 4/5, 2024 at 1:32 Comment(0)
C
-1

Another way:

DECLARE @MemoryTable table (
    RowID int,
    value_1 int,
    value_2 int,
    value_3 int
)

INSERT INTO @MemoryTable
SELECT ROW_NUMBER() OVER (ORDER BY value_1) AS RowID, * FROM SampleTable


DECLARE @ctr INT
DECLARE @MaxRownum INT

DECLARE @val1 INT
DECLARE @val2 INT
DECLARE @val3 INT


SET @ctr = 1
SET @MaxRownum = (SELECT COUNT(1) FROM @MemoryTable)


WHILE @ctr <= @MaxRownum
BEGIN

    SELECT @val1 = value_1,
           @val2=value_2,
           @val3=value_3
    FROM @MemoryTable
    WHERE RowID = @ctr

    exec spProcedure @val1, @val2, @val3

    SET @ctr = @ctr + 1
END
Cockeyed answered 11/6, 2014 at 7:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.