Professional Documents
Culture Documents
Retrieving one row or block of rows from the current position in the
result set.
Supporting data modifications to the rows at the current position in the
result set.
Supporting different levels of visibility to changes made by other users
to the database data that is presented in the result set.
Providing Transact-SQL statements in scripts, stored procedures, and
triggers access to the data in a result set.
Types of Cursors:
Static cursors
Dynamic cursors
Forward-only cursors
Keyset-driven cursors
Static cursors detect few or no changes but consume relatively few resources
while scrolling, although they store the entire cursor in tempdb. Dynamic
cursors detect all changes but consume more resources while scrolling,
although they make the lightest use of tempdb. Keyset-driven cursors lie in
between, detecting most changes but at less expense than dynamic cursors.
Cursor Statements:
We can control the records of a result set with the use of these cursor
statements. They are:
DECLARE
OPEN
FETCH
CLOSE
DEALLOCATE
OPEN Statement starts using the cursor. It executes the select statement
in the cursor and points the cursor to the first record of the result set.
FETCH statement is used to retrieve the data in the current location and
navigate the cursor to the required position.
CLOSE statement stops using the cursor. But the resources used by the
cursor are still open.
@@FETCH_STATUS:
Returns the status of the last cursor FETCH statement issued against any cursor
currently opened by the connection.
Example:
Suppose there is a table with some data and indexes. After the index
creation, if any modifications are performed on the table, those changes will not
reflect directly into the index structure. We have to refresh the index structure on
all table using the following statement.
DBCC DBREINDEX (<tablename>)
The above command should be executed for all tables of the database. To
perform this task we can make use of the following cursor program:
open tblcursor
while @@fetch_status=0
begin
dbcc dbreindex(@tblname)
fetch next from tblcursor into @tblname
end
close tblcursor
deallocate tblcursor