Friday, 23 January 2015

SQL SERVER CURSORS

CURSORS : - In Simple words, Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis,


--======================================================
-- SINGLE  VARIABLE AS INPUT TO EXEC PROCEDURE which takes only one variable as input
--======================================================

DECLARE @CLIENTKEY INT           
DECLARE CLIENTKEYCURSOR CURSOR
              FOR SELECT ID FROM customer 
OPEN CLIENTKEYCURSOR                                    -- open cursor
                                                       -- DO SOMETHING USEFUL
       FETCH NEXT FROM CLIENTKEYCURSOR                 -- fetch record
       INTO @CLIENTKEY
       WHILE @@FETCH_STATUS = 0
              BEGIN 
                     FETCH NEXT FROM CLIENTKEYCURSOR   -- loop through every record
                           INTO @CLIENTKEY
                           EXEC dbo.uspUpdateClientDate @CLIENTKEY
                           --SELECT   @CLIENTKEY
               END         
CLOSE CLIENTKEYCURSOR                                  -- close cursor
DEALLOCATE CLIENTKEYCURSOR                             -- deallocate cursor




--======================================================
---- MORE THAN ONE VARIABLE AS INPUT TO EXEC PROCEDURE which takes three variable as input
--======================================================



DECLARE @ID INT,@NAME VARCHAR(100), @AD VARCHAR(100)
DECLARE  NAMECURSOR CURSOR
               FOR SELECT ID, NAME, [ADD] FROM CUSTOMER
OPEN NAMECURSOR
              FETCH NEXT FROM NAMECURSOR
                     INTO @ID, @NAME, @AD
       WHILE @@FETCH_STATUS = 0
       BEGIN
              FETCH NEXT FROM NAMECURSOR
                     INTO @ID, @NAME, @AD
           EXEC [dbo].[UspInsertCustomerDetails] @ID, @NAME, @AD
       END
CLOSE NAMECURSOR

DEALLOCATE NAMECURSOR

No comments:

Post a Comment