Cursors in MSSQL – Copy/Paste template
February 23, 2010
Leave a comment
DECLARE @myName varchar(50)
DECLARE @myDesc varchar(50)
DECLARE myCursor CURSOR FOR
SELECT Name, Description
FROM Table
WHERE ID = @parameter
OPEN myCursor
FETCH NEXT FROM myCursor INTO @myName, @myDesc
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @myName + '; ' + @myDesc
FETCH NEXT FROM myCursor INTO @myName, @myDesc
END
CLOSE myCursor
DEALLOCATE myCursor
Reminder: Use unique cursor names! (if calling a procedure inside cursor which uses a cursor itself, the cursor names need to be unique)