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)

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close