SQL Cursors

There is usually a better way than to use cursors, but when it cannot be avoided, template:


DECLARE @myID INT
DECLARE @myID2 INT
DECLARE mycursor CURSOR
  FOR SELECT ID, ID2 FROM MyTable

OPEN mycursor
FETCH NEXT FROM mycursor INTO @myID, @myID2

WHILE @@FETCH_STATUS=0
BEGIN
  -- do stuff
  FETCH NEXT FROM mycursor INTO @myID, @myID2
END

CLOSE mycursor
DEALLOCATE mycursor
Advertisements