This is a mistake at a time. Here's the best way to iterate over a cursor without duplicating code:
USE Northwind GO DECLARE myCursor CURSOR FOR SELECT TOP(10) ContactName FROM Customers DECLARE @RowNo int,@ContactName nvarchar(30) SET @RowNo=0
For extra points, use the cursor variable and declare w / FAST_FORWARD and TYPE_WARNING or STATIC for small datasets. eg:
DECLARE @cursor CURSOR SET @cursor = CURSOR FAST_FORWARD TYPE_WARNING FOR SELECT TOP (10) ContactName FROM Customers OPEN @cursor ...... CLOSE @cursor DEALLOCATE @cursor
CLOSE and DEALLOCATE are not strictly necessary, as the cursor variable goes out of scope at the end of the batch. However, this is a good form, as you can add more code at the end later, and you should free up resources as soon as possible.
TYPE_WARNING tells you when SQL Server implicitly converts the requested cursor type (FAST_FORWARD) to another type (usually STATIC) if the requested type is not compatible with the SELECT statement.
source share