Thursday 4 April 2013

SQL Cursor Example


     To use cursors in SQL Server, you need to do the following steps:

-- (1) Declare a cursor that defines a result set.
-- (2) Open the cursor to establish the result set.
-- (3)  Fetch the data into local variables as needed from the cursor.
-- (4) Close the cursor when done.
-- (5) Deallocate the cursor.


declare cr2 cursor for select id from fst 
open cr2
fetch from cr2;
close cr2
deallocate cr2

-----------------------------------------------------------
 ---  Use Cursor on a Table 'fst' to featch 'id' column records

declare cr1 cursor for select id from fst 
declare @id int;
open cr1
fetch from cr1 into @id;
while @@FETCH_STATUS = 0
begin
print @id
fetch from cr1 into @id
end
close cr1
deallocate cr1


No comments:

Post a Comment