SQLServer cursor (Cursor) (B)

Cursor (Cursor) is a method for processing data, in order to see or deal with the result set of data, provides a cursor to the line or multi-line forward or ability to focus on the results of browsing data back. We can put the cursor as a pointer, it can specify any position in the result, and then allow the user to specify the location of data for processing.

      Composition of the cursor

      Cursor contains two parts: one is the result set cursor, a cursor position is.

      Cursor result set: Define this SELECT statement returns the cursor to obtain a set of rows. Cursor position: pointer to the current result set of a row.

 

      2. Classification of the cursor

      Cursor There are three categories: API server cursors, Transaction-SQL cursors and API client cursor.

      Of which the first two cursors are running on the server, it is also known as server cursor.

      API server cursor

      API server cursors are used in the service, when the client application calls API cursor function, API server will function for processing. Using the API functions and methods can achieve the following functions:

      (1) open a connection.

      (2) setting defines characteristics or attributes of the cursor feature, API cursor automatically mapped to each result set.

      (3) performing one or more Transaction-SQL statements.

      (4) extracting rows in the result set using the API function or method.

      API server cursor contains the following four categories: static cursors, animated cursors, forward-only cursor, a keyset-driven cursor (Primary key)

      Static cursor establish the full open cursor result set result set is stored in a temporary table (static cursors are always read-only). Static cursor has the following characteristics: always is displayed as the result set when the cursor is opened; the database does not reflect any changes made, the result does not reflect the changes made to the column values set rows; do not show the cursor is opened in a new database inserted rows; the result set of rows to be updated to other users, the new data values are not displayed in the static cursor; but static cursor displays rows after opening the cursor deleted from the database.

      Dynamic cursor and static cursors Conversely, when the dynamic cursor scrollable cursors reflect all changes in the result set. Line data in the result set value, and members of the order will change every time extraction.

      Only cursor does not support scrolling, cursor from start to finish it only supports order to extract the data line. Note: only cursor reflects all changes made to the result set.

      Keyset-driven cursor while the cursor has the characteristics of static and dynamic cursor. When the cursor is opened, the order of the row and the cursor member is fixed, at cursor open keyset is also stored in the temporary work table, change the data value of the non-key columns may be set at a user when scrolling the cursor see, after the cursor is opened to insert a row in the database is not visible, unless you turn off reopen the cursor.

 

      Transaction-SQL cursors

      The cursor is based Declare Cursor grammar, mainly for Transaction-SQL scripts, stored procedures and triggers. Transaction-SQL cursor processing server sent by the client to the server Transaction-SQL statements.

      Transaction-SQL cursor using the stored procedure or trigger process:

      (1) Transaction-SQL statement variable contains the data returned by the cursor. Set Column declare a variable for each result. Statement large enough to hold the value of the column variable return, and declare variables to be obtained from the type of data type implicit conversion of data types.

      (2) using the Declare Cursor statement Transaction-SQL cursors associated with the Select statement. Declare Cursor can also use the cursor definition read-only-forward characteristic. 

      (3) using the Open statement executes Select statements to populate the cursor.

      (4) Fetch Into sentence extracting a single row, and each column to obtain the variable data specified in the move. Note: Other Transaction-SQL statement can reference the values ​​of those variables to access the data extraction. Transaction-SQL cursors do not support the extraction line block.

      (5) use the Close statement to end the use of the cursor. Note: After closing a cursor still exists, you can use the Open command to open continue to be used only to call Deallocate statement will be fully released.

      Client cursors

      The cursor result set the default cache the entire result set on the client, all cursor operations were carried out in the client's cache. Note: The client-side cursors support only forward-only and static cursors. Other cursors are not supported.

 

      3. Cursor lifecycle

      Vernier's life cycle consists of five stages: declare a cursor, open the cursor, read the cursor data, close the cursor and release the cursor.

      Declare the cursor is designated as the cursor Select statement used to get data, and the cursor statement does not retrieve any data, it is only appropriate for the cursor indicates the Select statement.

      Declare Cursor name Cursor parameters

      Declare cursor parameters

            (1) Local and Global: Local shows the effect of it is limited to only the cursor in stored procedures, triggers, and batch, the cursor is automatically released after serving. Global cursor indicates that the entire scope of the session layer. Any connection procedure stored by the execution, and so can reference the cursor batch name, only implicitly deallocated when disconnected.

            (2) Forward_only and Scroll: the former is expressed only cursor shows the latter can be freely positioned. The default is the former.

            (3) Static, Keyset and Dynamic: the first return represents a definition of a cursor, which data is stored into a temporary table, all responses to all requests from the temporary table cursor, therefore, the data extraction operation cursors It does not reflect the changes made to the base table, and the cursor can not be modified. Keyset indicates that, when the cursor is opened, and the sequence identity keyset-driven cursor rows is fixed, and put it into a temporary table. Dynamic representation is scrollable cursors, animated cursors reflect all changes to the data in the result set.

            (4) Read_only, Scroll_Locks and Optimistic: a first read-only cursor indicates, represents the second lock is placed on the cursor result set of data used when the row is then read into the cursor to modify them, the database these lines will be locked to ensure data consistency. Optimistic meaning data is read after the cursor, if these data are updated, you will not succeed by updating and deleting cursor positioning operations carried out.

      Standard Miniature:

            Declare MyCursor Cursor 
                   For Select * From Master_Goods

      Read-only cursors

            Declare Cursor MyCusror

                  For Select * From Master_Goods

                  For Read Only

      Updatable cursors

            Declare Cursor MyCusror

                  For Select * From Master_Goods

                  For UpDate

      Open cursor using the Open Transaction-SQL statement to open server cursor, Open statement execution is filled in accordance with the Select statement data, position the cursor on the first line is opened after the cursor.

      Open the cursor

            Global cursor: Open Global MyCursor local cursor: Open MyCursor

      Reading cursor data : after the cursor is opened, using Fetch statement to retrieve a particular line from the Transaction-SQL server cursor. Use Fetch operation, moves the cursor to the next record, and each column of the cursor to return data obtained were assigned to the local variable declarations.

            Fetch [Next | Prior | First | Last | Absolute n | Relative n ]  From MyCursor

            Into @GoodsID,@GoodsName

            Wherein: Next returns the result set represents the recording current line to the next row, the first row if the first read is returned. The default read option for the Next

                   Prior to return a result set indicates a row before the current line, if the first row is read is not returned, and the cursor is placed before the first row.

                   First row represents a first return result set, and the current row.

                   Last indicates the last row of the result set returned, and the current row.

                   Absolute n if n is a positive number, starting from the n-th row is returned head cursor, and returns the row becomes the new current line. If n is negative, the n-th row starting from the end of the cursor returns, and returns the new behavior of the current line, if n is 0, the current row is returned.

                   Relative n if n is a positive number, the current from the n-th row lines beginning, if n is negative, the process returns from the n-th row preceding the current row, if it is 0, the current row is returned is returned.

      Close the cursor call is Close statement, as follows: Close Global MyCursor Close MyCursor

      Cursor release call is Deallocate statement, as follows: Deallocate Glboal MyCursor Deallocate MyCursor

 

      Cursor Example:

            Declare MyCusror Cursor Scroll

                  For Select * From Master_Goods Order By GoodsID

            Open MyCursor

            Fetch next From MyCursor
            Into @GoodsCode,@GoodsName

            While(@@Fetch_Status = 0)
                  Begin

                         Begin
                               Select @GoodsCode = Convert(Char(20),@GoodsCode)
                               Select @GoodsName = Convert(Char(20),@GoodsName)
                               PRINT @GoodsCode + ':' + @GoodsName
                         End

                         Fetch next From MyCursor
                         Into @GoodsCode,@GoodsName

                  End
            Close MyCursor
            Deallocate MyCursor

 

      Modify the current cursor data as follows:

            UpDate Master_Goods Set GoodsName = 'yangyang8848' Where Current Of MyCursor;
      delete the current cursor line data is as follows: 
            the Delete Current Of the Where the From Master_Goods MyCursor

 

      Select @@ CURSOR_ROWS number of rows can be present in the current cursor. Note: This global variable is a variable in the connection, thus corresponding to only the last open cursor.

 

Reproduced in: https: //www.cnblogs.com/llbofchina/p/3656287.html

Guess you like

Origin blog.csdn.net/weixin_34279184/article/details/94206601