====== Cursors ====== This is a template for cursor boilerplate, if you must. ''variableList'' is a list of variables, assumed already declared. DECLARE _myCursor CURSOR LOCAL FOR SELECT statement -- query to return the results you want to step through -- open the cursor and get the first row OPEN _myCursor FETCH NEXT FROM _myCursor INTO variableList WHILE @@FETCH_STATUS = 0 -- i.e. while the last FETCH NEXT returned a row BEGIN /* * Do some work here, presumably * using the values in variableList. */ -- get the next row nextRow: -- label useful here for CONTINUE effect FETCH NEXT FROM _myCursor INTO variableList END -- close and 'undeclare' the cursor CLOSE _myCursor DEALLOCATE _myCursor The ''nextrow'' label allows you to use ''GOTO nextRow'' in the ''WHILE'' body to achieve a ''CONTINUE'' effect without omitting to ''FETCH NEXT''. ===== Uncommented ===== DECLARE _myCursor CURSOR LOCAL FOR SELECT statement OPEN _myCursor FETCH NEXT FROM _myCursor INTO variableList WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM _myCursor INTO variableList END CLOSE _myCursor DEALLOCATE _myCursor {{tag> tsql development}}