T-SQL Looping through Query Results
Suppose you have a query that retrieves a list of IDs from a table:
SELECT @id=table.id FROM table
You then need to execute a stored procedure for each row, passing in the ID and another value:
EXEC stored_proc @varName=@id, @otherVarName='test'
In T-SQL, you can accomplish this using a CURSOR:
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
In this script:
This script allows you to loop through the query results and execute the stored procedure for each row, updating the variable names and values based on the data in the query.
The above is the detailed content of How Can I Iterate Through T-SQL Query Results and Execute a Stored Procedure for Each Row?. For more information, please follow other related articles on the PHP Chinese website!