You see things; and you say 'Why?' But I dream things that never were; and I say 'Why not?'

Monday, December 8, 2008

Cursors

Cursor
A cursor is a database object that applications use to manipulate data by rows instead of recordsets. You can use cursors to perform multiple operations in a row-by-row manner, against the resultset. You can do this with or without returning to the original table. In other words, cursors conceptually return a resultset based on tables within a database.

You can use the cursors to do the following:


In order to work with a cursor we need to perform some steps in the following order:

Declare cursor.
Open Cursor.
Fetch row from the cursor.
Process Fetched row.
Close cursor.
De allocate cursor.


Creating a Cursor

You can use the following two methods to create a cursor in SQL Server:

  1. The T-SQL language, which supports the syntax for using cursors modelled after the Sql-92 cursor syntax.
  2. Database application programming interface.

In this article, we will focus on T-SQl cursors. The syntax of T-SQL cursors and API cursors is different, but they follow a common sequence of steps.

Follow these steps to create a cursor:

  1. Associate a cursor with a resultSet of a T-SQL statement, and define the characteristics of the cursor, such as how the rows are going to be retrieved, and so forth.
  2. Execute the T-SQL statement to populate the cursor.
  3. Retrieve the rows in the cursor. The operation to retrieve one row or a set of rows is called fetch. Scrolling is a series of fetch operations to retrieve the rows in a backward or forward direction.
  4. You can also perform the modifications on a row at the cursor position.
  5. Close the cursor.
Syntax
  1. Use the DECLARE statement to create the cursor. It contains a SQL statement to include the records from the table.
  2. DECLARE  CURSOR FOR
    <Select Statement>
  3. After creating the cursor, you will open it. Use the OPEN statement to make the cursor accessible.
  4. OPEN 
  5. Use the FETCH statement to obtain the records from the cursor for further processing.
  6. FETCH 
  7. Use the CLOSE statement to temporarily close the cursor when it is not required. This statement releases the current resultset to close an open cursor. You have to re-open the cursor to fetch the rows.
  8. CLOSE 
  9. When you no longer require the cursor, you can use the DEALLOCATE statement to remove its reference.
  10. DEALLOCATE 

Fetching and Scrolling Through a Cursor

When you open a cursor, the current row pointer in the cursor is logically before the first row. T-SQL cursors can fetch one row at a time. The options for FETCH operations are as follows:

FETCH FIRST Fetches the first row in the cursor
FETCH NEXT Fetches the row after the previously fetched row
FETCH PRIOR Fetches the row before the previously fetched row
FETCH LAST Fetches the last row in the cursor
FETCH ABSOLUTE n If n is a positive integer, it fetches the nth row in a cursor. If n is a negative integer, it fetches the nth row before the last row. If n is 0, no row is fetched.
FETCH RELATIVE n If n is positive, it fetches the nth row from the previously fetched row. If n is negative, it fetches the nth row before the previously fetched row.If n is 0, the same row is fetched again.

By default, the FETCH NEXT option works. To use other options, you must include certain options in the DECLARE statement while creating the cursors.


DECLARE Statement Options

You can add the following attributes to the cursor to enhance its scrollability of a cursor. The attributes also are explained in the following list.

DECLARE  CURSOR
[LOCAL | GLOBAL]
[FORWARD ONLY | SCROLL]
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD]
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]
[TYPE_WARNING]
FOR
[FOR UPDATE [OF Column_name[,....N]]]

The cursor is implicitly deallocated when the batch, stored procedure, or trigger terminates, unless the cursor was passed back in an OUTPUT parameter. If it is passed back in an OUTPUT parameter, the cursor is deallocated when the last variable referencing it is deallocated or goes out of scope.

  • GLOBAL: Specifies that the scope of the cursor is global to the connection. The cursor name can be referenced in any stored procedure or batch executed by the connection. The cursor is only implicitly deallocated at disconnect.
  • FORWARD_ONLY: Specifies that the cursor can only be scrolled from the first to the last row. FETCH NEXT is the only supported fetch option. If FORWARD_ONLY is specified without the STATIC, KEYSET, or DYNAMIC keywords, the cursor operates as a DYNAMIC cursor.

    When neither FORWARD_ONLY nor SCROLL is specified, FORWARD_ONLY is the default, unless the keywords STATIC, KEYSET, or DYNAMIC are specified. STATIC, KEYSET, and DYNAMIC cursors default to SCROLL. Unlike database APIs such as ODBC and ADO, FORWARD_ONLY is supported with STATIC, KEYSET, and DYNAMIC Transact-SQL cursors. FAST_FORWARD and FORWARD_ONLY are mutually exclusive; if one is specified, the other cannot be specified.

  • STATIC: Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications.
  • KEYSET: Specifies that the membership and order of rows in the cursor are fixed when the cursor is opened. The set of keys that uniquely identify the rows is built into a table in tempdb known as the keyset. Changes to nonkey values in the base tables, either made by the cursor owner or committed by other users, are visible as the owner scrolls around the cursor. Inserts made by other users are not visible (inserts cannot be made through a Transact-SQL server cursor).

    If a row is deleted, an attempt to fetch the row returns an @@FETCH_STATUS of -2. Updates of key values from outside the cursor resemble a delete of the old row followed by an insert of the new row. The row with the new values is not visible, and attempts to fetch the row with the old values return an @@FETCH_STATUS of -2. The new values are visible if the update is done through the cursor by specifying the WHERE CURRENT OF clause.

  • DYNAMIC: Defines a cursor that reflects all data changes made to the rows in its result set as you scroll around the cursor. The data values, order, and membership of the rows can change on each fetch. The ABSOLUTE fetch option is not supported with dynamic cursors.
  • FAST_FORWARD: Specifies a FORWARD_ONLY, READ_ONLY cursor with performance optimizations enabled. FAST_FORWARD cannot be specified if SCROLL or FOR_UPDATE is also specified. FAST_FORWARD and FORWARD_ONLY are mutually exclusive; if one is specified, the other cannot be specified.
  • READ_ONLY: Prevents updates from being made through this cursor. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides the default capability of a cursor to be updated.
  • SCROLL_LOCKS: Specifies that positioned updates or deletes made through the cursor are guaranteed to succeed. Microsoft SQL Server locks the rows as they are read into the cursor to ensure their availability for later modifications. SCROLL_LOCKS cannot be specified if FAST_FORWARD is also specified.
  • OPTIMISTIC: Specifies that positioned updates or deletes made through the cursor do not succeed if the row has been updated since it was read into the cursor. SQL Server does not lock rows as they are read into the cursor. It instead uses comparisons of timestamp column values, or a checksum value if the table has no timestamp column, to determine whether the row was modified after it was read into the cursor. If the row was modified, the attempted positioned update or delete fails. OPTIMISTIC cannot be specified if FAST_FORWARD is also specified.
  • TYPE_WARNING: Specifies that a warning message is sent to the client if the cursor is implicitly converted from the requested type to another.

    select_statement is a standard SELECT statement that defines the result set of the cursor. The keywords COMPUTE, COMPUTE BY, FOR BROWSE, and INTO are not allowed within a select_statement of a cursor declaration. SQL Server implicitly converts the cursor to another type if clauses in select_statement conflict with the functionality of the requested cursor type. For more information, see Implicit Cursor Conversions.

    UPDATE [OF column_name [,...n]] defines updatable columns within the cursor. If OF column_name [,...n] is supplied, only the columns listed allow modifications. If UPDATE is specified without a column list, all columns can be updated, unless the READ_ONLY concurrency option was specified

  • Properties of Cursors - 4 Types
    1. Scope of cursor.
    2. Cursor type.
    3. Navigation type.
    4. Lock type
    Scope of cursor:
    Scope may be local or global. Once we declare cursor in stored procedure as local then it can be accessible only with in stored procedure and if we declare cursor inside stored procedure as Global then it can be accessible outside the procedure execution also.

    Navigation Type:
    It can be forward_only (or) scroll.
    • Forward_Only: Allows processing of cursor only in forward direction.
    • Scroll: It allows processing of cursor result in any direction
    Cursor Types:

    Sql Server support 4 Types of cursors.
    a)Static
    Static cursor takes more memory, any operations in the tables is not reflected in static cursor result.
    b)Keyset:
    Keyset cursor takes less memory. deletions and updations in the tables are reflected in keyset cursor.
    c)Fast_Forward:
    It is similar to keyset cursor, it gives high performance and fast_forward cursor allows you to process the cursor result forward_only.
    d)Dynamic:
    Any operations in the tables is dynamically reflected in dynamic cursor. Dynamic cursor gives less performance. It does not allow to process a particular position in a row.

    Lock Type:
    We can apply three types of locks on cursors
    a)Read_Only[shared lock]
    We can perform only read operation on cursor result.
    b)Scroll_locks[Exclusive lock]
    We can perform modifications in the cursor result also and only one user can modify cursor result at a time.
    c)Optimistic[Update lock]
    We can perform modifications in the cursor result also, multiple users can modify cursor result at a time.
    ------------------------
    Absolute Position or Relative Position

    Absolute Position always fetches the particular position row which starts from the beginning of the cursor.

    Relative Position can fetch the particular position of the row, based on current position. relative may be positive or negative.

    Advantages of Cursors
    1. Cursor allows us to process the result row by row and printing in formatted results.
    2. we can perform batch operations, deletions in the table through cursor result updations.
    Drawbacks of Cursors
    1. Cursor degrades the performance while processing row by row.
    2. Alternative is user defined functions, common table expressions.

    No comments:

    Followers