Wednesday 12 July 2017

CURSOR EXAMPLE IN SQL SERVER

--========= CURSOR SAMPLE EXAMPLE ============
/*
A cursor is temparory work area created in system memory when  a sql statement executed. Cursor contains information on selected statement and
the row of data access by it.This temporary work area is used to store the data retrieved from the database, and manipulate
this data.

*/
CREATE TABLE #tblEmployee
(
EmpId int primary key identity(1,1),
Mobile varchar(10)
)
insert into #tblEmployee (Mobile)
VALUES
('9899767121'),
('7546434534'),
('9656345433'),
('7898056566'),
('0986545445'),
('2342546456')

DECLARE  @EmpId int,@Mobile varchar(20)     -- declare variable which are used in cursor code block
DECLARE MyCursor CURSOR                     ---- declare cursor
 FOR --- There are an equal number of variables in the DECLARE CURSOR FOR statement as there are in the SELECT statement.        
 select EmpId,Mobile From #tblEmployee
 OPEN MyCursor -- OPEN Cursor
 FETCH NEXT FROM MyCursor INTO @EmpId,@Mobile   --- FETCH NEXT FROM  
 WHILE @@FETCH_STATUS=0 --- WHILE Statement
 BEGIN
   PRINT @Mobile
 
   FETCH NEXT FROM MyCursor INTO @EmpId,@Mobile
 END
 CLOSE MyCursor ---CLOSE statement - Releases the current data and associated locks, but permits the cursor to be re-opened
 DEALLOCATE MyCursor ---DEALLOCATE statement - Destroys the cursor

No comments:

Post a Comment