Monday 6 June 2016

What is cursor and how to use in sql server?

Cursor: Cursor is basically a database object to retrieve data row by from resultset. cursor is used to loop through a resultset.

Steps to use cursor:

declare @studentid int

1. Declare Cursor-

DECLARE @MyCursor CURSOR

2. Set Cursor

SET @MyCursor = CURSOR FAST_FORWARD
FOR
select studentid from tbl_students

3.Open Cursor

OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @studentid
WHILE @@FETCH_STATUS = 0

WHILE @@FETCH_STATUS = 0//loop till last row

BEGIN
 query you want to execute
END

4. Close Cursor

CLOSE @MyCursor

5. Deallocate Cursor

DEALLOCATE @MyCursor

No comments:

Post a Comment