Search code examples
sqlt-sql

T-SQL loop over query results


I run a query select @id=table.id from table and I need to loop over the results so I can exec a store procedure for each row exec stored_proc @varName=@id,@otherVarName='test'

How can I do this in a T-SQL script?


Solution

  • You could use a CURSOR in this case:

    DECLARE @id INT
    DECLARE @name NVARCHAR(100)
    DECLARE @getid CURSOR
    
    SET @getid = CURSOR FOR
    SELECT table.id,
           table.name
    FROM   table
    
    OPEN @getid
    FETCH NEXT
    FROM @getid INTO @id, @name
    WHILE @@FETCH_STATUS = 0
    BEGIN
        EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
        FETCH NEXT
        FROM @getid INTO @id, @name
    END
    
    CLOSE @getid
    DEALLOCATE @getid
    

    Modified to show multiple parameters from the table.