Cursor

CURSOR

This can be defined as a memory are in which result of a query is started. If you want to use a multiple raw select in a stored procedure you need to create a cursor.

SQL Server is very good at handling sets of data. For example, you can use a single UPDATE statement to update many rows of data. There are times when you want to loop through a series of rows a perform processing for each row. In this case you can use a cursor.

Step 01

Declare the Cursor

When you declare the cursor, we tell the server to allocate memory for the query, which is to be executed.

Step 02

Open the Cursor

The Query actually gets executed a results set is created and the cursor points to the first Record.

Step 03

Fetch the Records one by one from the results set using a loop.

Step 04

Close the Cursor

Step 05(optional)

De-allocates the memory occupied by the Cursor.

Eg:1

DECLARE CUR1 CURSOR FOR SELECT * FROM EMPLOYEES WHERE DEPTNO=20

OPEN CUR1

FETCH NEXT FROM CUR1

WHILE @@FETCH_STATUS =0

BEGIN

FETCH NEXT FROM CUR1

END

CLOSE CUR1

DEALLOCATE CUR1


Eg:2

DECLARE @EN VARCHAR(20), @S INT

DECLARE CUR2 CURSOR FOR SELECT ENAME,SAL FROM EMPLOYEES WHERE DEPNO=20

OPEN CUR2

FETCH NEXT FROM CUR2 INTO @EN, @S

WHILE @@FETCH_STATUS=0

BEGIN

PRINT @EN

PRINT @S

FETCH NEXT FROM CUR2 INTO @EN, @S

END

CLOSE CUR2

DEALLOCATE CUR2