Simple SQL Cursor Example
If you’re reading this blog, chances are, you know how to write/use a SQL cursor. But this is more for my benefit, and maybe even yours. Just a quick cursor example, so that I can easily reference the syntax if I ever need to quickly look it up, since I always seem to forget it. Enjoy.
DECLARE @CONTACTID INT --will need to declare at least one variable
--in this case, to store values when iterating through cursor DECLARE SIMPLE_CURSOR CURSOR FOR SELECT ID FROM CONTACT OPEN SIMPLE_CURSOR FETCH NEXT FROM SIMPLE_CURSOR --Start the cursor INTO @CONTACTID WHILE @@FETCH_STATUS = 0 --while there is a loaded record, keep processing BEGIN --do whatever you need to do print ('This is where the magic happens! Do whatever you need to do (update/insert/delete/stored proc/etc.') FETCH NEXT FROM SIMPLE_CURSOR INTO @CONTACTID --fetch next record END CLOSE SIMPLE_CURSOR --close and deallocate DEALLOCATE SIMPLE_CURSOR