Cursors in MSSQL – Copy/Paste template

    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)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: