- Allows row-by-row processing. Control will be with user rather than SQL server
- Different options can be applied while creating a cursor
o Local/global
o Static/dynamic/fast_forward/ketyset driven
o Forward_only/scroll
- Generally it should be avoided as it is affecting a performance a big time
- If another SP is being called within cursor, it will fail. So while loop should be used instead of cursor
- A general syntax
DECLARE cur CURSOR
FOR SELECT a,b FROM TableName
OPEN cur
FETCH NEXT FROM Cur INTO @a, @b
WHILE @@FETCH_STATUS = 0
BEGIN
-- Your logic
FETCH NEXT FROM Cur INTO @a, @b
END
CLOSE cur
DEALLOCATE cur
- In some cases, Cursor will be faster than normal join e.g.
- when there is some N level of parent-child relationship than rather than joining the same table multiple times, we can use cursor and achieve the results fast
- When you have to insert millions of record in one table then probably you can start cursor and insert a bunch of records (let's say 25K records) in chunks which will be faster than a single INSERT statement
- Even if we have to use cursor, it is recommended that we use WHILE LOOP rather than using cursor
Keyset-Driven Cursor
Introduction
In this article I describe keyset-driven cursor. With the help of keyset-drivin cursor we can find first, next, last and any specific row of the table.
First we create a table named emp to apply a cursor on this table:
Creation of table
create table emp(emp_id int,em_name varchar(10))
go insert into emp select 1,'d' union all select 2,'e' union all select 3,'f' union all select 4,'mahi' union all select 5,'gill' union all select 6,'singh' go select * from emp |
Output:
Keyset-driven cursor:
It lies between a static and a dynamic cursor. When we open keyset-drivin cursor than it saves the list of unique values for the entire result set, these values are called keyset. These keys retrieve the current data values for each row.
Creation of Keyset-drivin cursor:
declare key_cursor cursor
keyset for select * from emp |
Opening of Keyset-drivin cursor:
We open a Keyset-drivin Cursor as in the in following:
open key_cursor
|
Fetching first data from Keyset-drivin Cursor:
fetch firstfrom key_cursor
|
Outout:
Closing the Keyset-drivin Cursor:
We close Keyset-drivin Cursor as in the following
close key_cursor
|
Dealloting Keyset-drivin Cursor:
We deallocate Keyset-drivin Cursor as following
SQL SERVER – Examples of Cursors
Static Cursor - Example
Dynamic Cursor - Example
Forward Only Cursor - Example
Keyset Driven Cursor - Example
|
No comments:
Post a Comment