At the end of this presentation you should be able to:
Understand the concept of cursor
Understand why cursor is required in a database
Understand the different types of cursors
Working with cursor
What is a Cursor
A cursor is a database object that helps in accessing and manipulating row by row data in a given result set.
Cursor serves as a mechanism for an application to operate on a single row or a small set of rows .
What is a Cursor (Continued)
It allows specific rows to be retrieved from result set
It allows the current row in result set to be modified
Helps to navigate from the current row in the result set to a different row
Allows data to be modified by other users to be visible in the result set.
Types of Cursors
Cursors can be classified as follows:
Types of cursors (Continued) Forward_only cursor is the one which doesn’t support backward scrolling .This cursor only fetches rows in a serial order ,i.e. from beginning of the result set till end. The rows from the database are retrieved only if these are explicitly fetched. The changes made by an INSERT , UPDATE and DELETE operations are reflected only when the rows are fetched from cursors Forward_ only It is a cursor that does not reflect any kind of modification that has been made either to the associated tables in the database or to the result set of the cursor itself. Hence, none of the UPDATE,DELETE or INSERT operations is reflected in the cursor unless it is closed and reopened Static Description Cursor Type
Types of Cursors (Continued) Description Cursor Type Dynamic cursors are cursors that reflect all the changes that have been made to the result set while scrolling through it . All changes caused by any of the INSERT, UPDATE or DELETE operations are reflected in these cursors Dynamic keyset driven cursors are cursors that show changes in the result set caused by UPDATE and DELETE statement while the cursor is open but do not reflect the changes caused by the INSERT operation Keyset driven
To work with Cursors
The following process defines the working of a cursor in SQL Server:
The cursor needs to be defined and its attributes need to be set.
The cursor needs to be opened
The required rows need to be fetched from the cursor
The data in the current row of the cursor can be modified, if required
To Work with Cursors (Continued)
User can define a cursor and its characteristics set by using the DECLARE CURSOR statement.