Loop in stored procedure on SQL server

I need help writing a stored procedure that calls another stored procedure and passes values ​​to it. So far this has been done in C #, now I want to move it to a stored procedure and execute the SQL agent job, which calls it at a specific time. Any ideas? In this case.

Table A:

PK_TableA_ID

Table B:

PK_TableB_ID

Stored Procedure SP1:

@TableA_ID
@TableB_ID

I need this, but in T-SQL

foreach(var TableAId in TableA)
{
foreach(var TableBId in TableB)
{
//call stored procedure 
SP1(TableAId, TableBId);
}
}
+4
source share
1 answer

Here is an example of how you can use cursors to create loops:

-- set up some test data
declare @table_a table (PK_TableA_ID int)
declare @table_b table (PK_TableB_ID int)
insert @table_a values (1),(2),(3)
insert @table_b values (4),(5),(6)    

-- do the actual processing
SET NOCOUNT ON

DECLARE @TableA_ID int, @TableB_ID int

DECLARE TableA_cursor CURSOR FOR SELECT PK_TableA_ID FROM @table_a

OPEN TableA_cursor
FETCH NEXT FROM TableA_cursor INTO @TableA_ID

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE TableB_cursor CURSOR FOR SELECT PK_TableB_ID FROM @table_b

    OPEN TableB_cursor
    FETCH NEXT FROM TableB_cursor INTO @TableB_ID

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT CAST(@TableA_ID AS CHAR(1)) + ':' + CAST(@TableB_ID AS CHAR(1))
        -- execute your stored procedure here:
        -- EXEC Your_stored_procedure (@TableA_ID, @TableB_ID) 
        FETCH NEXT FROM TableB_cursor INTO @TableB_ID
        END

    CLOSE TableB_cursor
    DEALLOCATE TableB_cursor

    FETCH NEXT FROM TableA_cursor INTO @TableA_ID
END 
CLOSE TableA_cursor
DEALLOCATE TableA_cursor

The cursor above (with test data in temporary tables) will generate this output:

1:4
1:5
1:6
2:4
2:5
2:6
3:4
3:5
3:6

.

+7

Source: https://habr.com/ru/post/1532001/


All Articles