Follow me on Twitter at Twitter.com/wbm
FYI, I'm blogging most of my stuff over at More Wally now.
You might want to add my rss feed to your reader at:http://morewally.com/cs/blogs/wallym/rss.aspx
SQL Cursor within a Trigger - Wallace B. McClure

Wallace B. McClure

All About Wally McClure - The musings of Wallym on Web, HTML5, Mobile, MonoTouch for iPhone, MonoDroid for Android, and Windows Azure.

News

Personal Blog

Work Blog

.NET

Book Authors

Business

Family

Friends

Georgia Tech Bloggers

Personal

Archives

SQL Cursor within a Trigger

Sometimes you need to create a Sql Cursor within a trigger.  I recently had a problem where that was the only way that I could get it to work reliably.  I am putting this up here for my personal reference.  I don't think that it is a particularly good example, just a skeleton that I would like to keep around.  Here is the code:

ALTER TRIGGER dbo.tr_lkOCRStaff_Update
ON dbo.lkOCRStaff
FOR UPDATE
AS
BEGIN
 SET NOCOUNT ON
 DECLARE @EDNETID NVARCHAR(20), @SFULLNAME NVARCHAR(50), @SLASTNAME NVARCHAR(25), @SFIRSTNAME NVARCHAR(25), @TEAMCODE NVARCHAR(4), @SPHONE NVARCHAR(20), @ACTIVE BIT, @LKOCRSTAFFID INT, @LKOCRTEAMID INT
 DECLARE STAFFCURSOR CURSOR FOR SELECT EDNETID, SFULLNAME, SLASTNAME, SFIRSTNAME, TEAMCODE, SPHONE, ACTIVE, LKOCRSTAFFID FROM INSERTED
 OPEN STAFFCURSOR
 FETCH NEXT FROM STAFFCURSOR INTO @EDNETID, @SFULLNAME, @SLASTNAME, @SFIRSTNAME, @TEAMCODE, @SPHONE, @ACTIVE, @LKOCRSTAFFID
 WHILE @@FETCH_STATUS = 0
 BEGIN
  SELECT @LKOCRTEAMID = (SELECT LKOCRTEAMID FROM DBAMS..LKOCRTEAM WHERE TEAMCODE=@TEAMCODE)
  UPDATE DBAMS..LKOCRSTAFF SET EDNETID=@EDNETID, SFULLNAME=@SFULLNAME, SLASTNAME=@SLASTNAME, SFIRSTNAME=@SFIRSTNAME,
   SPHONE=@SPHONE, LKOCRTEAMID=@LKOCRTEAMID WHERE LKOCRSTAFFID=@LKOCRSTAFFID
  FETCH NEXT FROM STAFFCURSOR INTO @EDNETID, @SFULLNAME, @SLASTNAME, @SFIRSTNAME, @TEAMCODE, @SPHONE, @ACTIVE, @LKOCRSTAFFID
   
 END
 CLOSE STAFFCURSOR
 DEALLOCATE STAFFCURSOR
END

Comments

Keith Rome said:

Be super careful with that.

One thing that is illegal within a trigger is performing DDL operations - such as creating a temp table. It is surprisingly easy to get in trouble that way.

Your code is OK as is, but be cautious about adding complex cursors or explicit temp tables.
# August 10, 2005 5:02 PM

Keith Rome said:

Oh, and you should also inspect @@cursor_rows <> 0 after opening and prior to fetching from the cursor -- its just an optimization step.
# August 10, 2005 5:05 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)