SQL Server - Cursor example

SQL Server - Cursor example

Sometimes we need to run loop on data, for that we need cursor. We can write our own business logic in cursor loop. 

Cursor is nothing but it is a loop like development code.

Here, I have mentioned cursor syntax with example. I hope you can use cursor easily as per your requirement...
-- Declare field variable
DECLARE @id INT
DECLARE @fname nvarchar(50)
DECLARE @lname nvarchar(50)
DECLARE @email nvarchar(50)

-- Declare Cursor name
DECLARE @curEmployee CURSOR

-- Set Cursor value
SET @curEmployee = CURSOR FOR
 SELECT id, EmailId, Firstname, LastName FROM Employee

OPEN @curEmployee

-- Loop Cursor
FETCH NEXT
 FROM @curEmployee INTO @id, @email, @fname, @lname
 WHILE @@FETCH_STATUS = 0
 BEGIN
  PRINT convert(nvarchar(10) , @id) + ' - ' + @fname + ' ' + @lname + ' -- ' + @email
  -- TODO
  -- Do your process 
 FETCH NEXT
 FROM @curEmployee INTO @id, @email, @fname, @lname
END

-- Close and deallocate Cursor
CLOSE @curEmployee
DEALLOCATE @curEmployee
 

 


Hope this will help you and save your time.

Enjoy !!!

:)

No comments:

Post a Comment