164 words
1 minute
T-SQL - syntactic sugar for updating current row in cursor
I am not a big fan of cursors, however for time to time I have to write one. In my case cursor usually is responsible for some complicated updates. Until yesterday I’ve been writing my update statements within the cursor the standard way
-- cursor code omitted for brevity-- some complicated updateUPDATE Person.Person set FirstName = 'some logic goes here' where Person.BusinessEntityID = @Idwhere @Id variable is set by cursor.-- cursor code omitted for brevityThere is nothing wrong with that, however we can do the same thing using specialized syntax - current of keyword(s)
UPDATE Person.Person set FirstName = 'some logic goes here' where current of personCursorThe entire cursor statement then looks that way
DECLARE personCursor CURSOR FOR SELECT top 1000 * FROM Person.PersonOPEN personCursorFETCH NEXT FROM personCursorWHILE @@FETCH_STATUS = 0BEGIN -- some complicated update goes here UPDATE Person.Person set FirstName = 'some logic goes here' where current of personCursor FETCH NEXT FROM personCursorENDCLOSE personCursorDEALLOCATE personCursor