Programmer's Corner - SQL Source Code Sample

Backup and Security Solutions 10% off all products with promo code: VISI-P1YR
Get the Programmer's Corner FireFox Search Plug-In

Stored Procedure Using Cursor - SQL

Anonymous

         

         

Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.

For example, you can use cursor to include a list of all user databases and make multiple operations against each database by passing each database name as a variable.





USE pubs
declare @Auth_Last as varchar(30)
DECLARE authors_cursor CURSOR FOR
SELECT au_lname FROM authors WHERE au_lname LIKE 'B%'
OPEN authors_cursor     -- Perform the first fetch.
FETCH NEXT FROM authors_cursor into @Auth_Last 
             -- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN        -- This is executed as long as the previous fetch succeeds.
   SELECT @Auth_Last as Auth_Last   
   FETCH NEXT FROM authors_cursor into @Auth_Last
END
CLOSE authors_cursor
DEALLOCATE authors_cursor
GO