SQL – How to Update Records in a Table Using a Loop and Cursor

I had a challenge yesterday that I would normally solve using some Visual Basic code but had to do it in pure SQL on a SQL 2005 server.

THE CHALLENGE:
Loop through all the records in a table and then update the table based on some logic or condition.

THE SOLUTION:

Using a SQL Cursor, I was able to loop through all the records in a table and then run an SQL update command for certain records that matched a particular criteria.

SQL Sample Code

DECLARE @myEmpID int

DECLARE MyCursor CURSOR FOR

SELECT DISTINCT  EmployeeID FROM Employees WHERE Company=64


OPEN myCursor


--Read the initial emploee id value from the cursor

FETCH NEXT FROM myCursor

INTO @myEmpID


WHILE @@FETCH_STATUS = 0


BEGIN

--Update goes here 

UPDATE Employees 

SET [Status] = 'T'


WHERE EmployeeID = @myEmpID AND Company=54


FETCH NEXT FROM MyCursor

INTO @myEmpID


END

CLOSE MyCursor

Author: Rick Cable / AKA Cyber Abyss

A 16 year US Navy Veteran with 25+ years experience in various IT Roles in the US Navy, Startups and Healthcare. Founder of FinditClassifieds.com in 1997 to present and co-founder of Sports Card Collector Software startup, LK2 Software 1999-2002. For last 7 years working as a full-stack developer supporting multiple agile teams and products in a large healthcare organization. Part-time Cyber Researcher, Aspiring Hacker, Lock Picker and OSINT enthusiast.