Wednesday, December 30, 2009

Cursor in sql server 2005

What Is Cursor
The typical SQL Commands operate on all row in the set at one time, but sometimes we need to manipulate data in a set on row - by - row basis, then the role of cursor comes in SQL. Cursor is a database object used to manipulate data in a set on a row-by-row basis by an application. 


The basic syntax of a cursor is:

 -- variable declaration
DECLARE @AuthorID char(11)
        
-- cursor declaration 
DECLARE c1 CURSOR READ_ONLY -- c1 is the cursor name
FOR
SELECT au_id  -- column name from which the values to be fetched
FROM authors -- table name on which cursor applies
 
OPEN c1  -- open the cursor
 
FETCH NEXT FROM c1  -- fetching row from table using cursor
INTO @AuthorID      -- column from which values to be get
 
WHILE @@FETCH_STATUS = 0 -- cheking the fetch status if 0 then row fetched 
                         -- else value is negative
BEGIN
 -- your code goes here like printing the author id got form cursor
        PRINT @AuthorID
 
        FETCH NEXT FROM c1 -- fetching next row from table using cursor
        INTO @AuthorID
 
END
 
CLOSE c1           -- closing cursor
DEALLOCATE c1      -- deallocating cursor from memory


No comments:

Post a Comment