Monday, February 16, 2015

SQL SERVER – Simple Example of Cursor with update table

A cursor is a set of rows together with a pointer that identifies a current row.

DECLARE cursor_activatedOnEmpty CURSOR FOR SELECT userid, statusid,RegisteredOn, activatedOn, RealActivationDate FROM UserProfile where statusID=1330 and  activatedOn is null; 
DECLARE @userid INT;
DECLARE @statusid INT;
DECLARE @RegisteredOn Date;
DECLARE @activatedOn Date;
DECLARE @RealActivationDate Date;
DECLARE @PreviousStatusID INT;
OPEN cursor_activatedOnEmpty;
FETCH NEXT FROM cursor_activatedOnEmpty INTO @userid, @statusid,@RegisteredOn, @activatedOn,@RealActivationDate;
WHILE @@FETCH_STATUS = 0  
BEGIN    
 
 SET @PreviousStatusID = (select top 2 StatusIDHeld from dbo.UserStatusHistory where userid=@userid order by statusChangedOn DESC)  
       if (@PreviousStatusID=1325)
       update UserProfile set activatedOn=@RegisteredOn where userid=@userid

       FETCH NEXT FROM cursor_activatedOnEmpty INTO @userid, @statusid,@RegisteredOn, @activatedOn,@RealActivationDate;
END;
CLOSE cursor_activatedOnEmpty;
DEALLOCATE cursor_activatedOnEmpty;

Happy Cursor!!

No comments:

Post a Comment