sql server loop over query 1

sql server loop over query

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

Here is what the above code is Doing:
1. Declaring variables to hold the values from the cursor
2. Declaring the cursor
3. Opening the cursor
4. Fetching the first row from the cursor
5. While there are still rows to fetch, execute the stored procedure with the values from the cursor
6. Fetch the next row from the cursor
7. Close the cursor
8. Deallocate the cursor

Similar Posts