Tuesday, January 26, 2010

How to Create a Cursor (small sample code)

declare @Variable nvarchar(50)
DECLARE Sample_cursor CURSOR FOR  select oldrecord from tblOldTable  --[declaring cursor for a select statement]

Open Sample_cursor --[opening cursor]
FETCH NEXT FROM Sample_cursor 
INTO @Variable [Getting a single record in to declared varaible]

WHILE @@FETCH_STATUS = 0 [checking fetch status to loop the cursor]
BEGIN

//Here you have to write your logic
Update set NewRecord = 'something'
from tblNewTable where oldrecord = @Variable
FETCH NEXT FROM Sample_cursor
INTO @Variable
End
CLOSE Sample_cursor
DEALLOCATE Sample_cursor

1 comment:

Anonymous said...

it saved my lot of time , thank you