Use of T-SQL Cursors

Cursors are similar to loop operations in java.

1. Define a cursor
A cursor can actually be understood as a pointer defined on a particular data set. We can control this pointer to traverse the data set or simply point to a specific row, so the cursor is defined on a data set that starts with Select:

 The cursor definitions in T-SQL are as follows in MSDN:
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] 
     [ FORWARD_ONLY | SCROLL ] 
     [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] 
     [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] 
     [ TYPE_WARNING ] 
     FOR select_statement 
     [ FOR UPDATE [ OF column_name [ ,...n ] ] ]
[;]

2. Parameters defined by cursors:
The cursor parameters are: LOCAL and GLOBAL two choices, FORWARD_ONLY and SCOLL two choices, STATIC KEYSET DYNAMIC and FAST_FORWARD four choices, READ_ONLY SCROLL_LOCKS OPTIMISTIC three choices.
(1) LOCAL and GLOBAL
LOCAL means that the lifetime of a cursor is visible only in batch or function or stored procedures, while GLOBAL means that the cursor is globally valid for a particular connection as a context. If the cursor scope is not specified, the default scope is GLOBAL.

--Define global cursors, which are global by default
DECLARE test_cursor cursor global for select * from EnSummation;

--Define local cursors
DECLARE test_cursor2 cursor local for select * from ExSummation;
--Can be used to end the scope above
go

open test_cursor;

--Opening here will cause an error.,because test_cursor2 Is defined as local,go After the scope is terminated, local reporting errors occur
open test_cursor2;

FORWARD_ONLY and SCOLL
FORWARD_ONLY means that the cursor can only be read from the data set to the end of the data set. FETCH NEXT is the only option, while SCROLL supports the cursor to move in any direction or anywhere in the defined data set.

--FORWARD_ONLY This means that the cursor can only be read from the data set to the end of the data set.,Can only be matched FETCH NEXT,Default is FORWARD_ONLY
DECLARE tst_cursor cursor  FORWARD_ONLY for select * from EnSummation;

--SCROLL Supporting cursors to move in any direction, or anywhere in a defined data set
DECLARE tst_cursor2 cursor SCROLL for select * from ExSummation;

open tst_cursor

open tst_cursor2

fetch next from tst_cursor

fetch last from tst_cursor -- Error Reporting,Because only with fetch nextUse together

fetch next from tst_cursor2

fetch last from tst_cursor2 

(3) STATIC KEYSET DYNAMIC and FAST_FORWARD

These four keywords are the relationship between the data in the table and the data read out by the cursor in the data set where the cursor is located.
STATIC means that when a cursor is created, a copy of the data set contained in the SELECT statement following FOR will be created and stored in the tempdb database. Any changes to the data in the underlying table will not affect the content of the cursor.
DYNAMIC is the opposite option to STATIC. When the underlying database changes, the content of the cursor is reflected. In the next fetch, the content of the data changes accordingly.
KEYSET can be understood as a compromise between STATIC and DYNAMIC. When any row in the result set is changed or deleted, @@FETCH_STATUS will be -2. KEYSET cannot detect the newly added data.
FAST_FORWARD can be understood as an optimized version of FORWARD_ONLY. FORWARD_ONLY executes a static plan, while FAST_FORWARD chooses a dynamic plan or a static plan according to the situation. In most cases, FAST_FORWARD performs slightly better than FORWARD_ONLY.
READ_ONLY SCROLL_LOCKS OPTIMISTIC
READ_ONLY means that the declared cursor can only read the data, and the cursor can not do any update operations.
SCROLL_LOCKS is another extreme, locking all data read into the cursor to prevent other programs from changing to ensure the absolute success of the update.
OPTIMISTIC is a relatively good choice. OPTIMISTIC does not lock any data. When it needs to update the data in the cursor, if the data in the underlying table is updated, the data in the cursor is unsuccessful. If the data in the underlying table is not updated, the data in the cursor can be updated.

3. Open the cursor
When the cursor is defined, the cursor needs to be opened and used with only one line of code:
OPEN test_Cursor
Note that when global and local cursor variables are renamed, the local variable cursor is opened by default
4. Close the cursor
After the cursor is used, be sure to close it, just one line of code: CLOSE + cursor name
CLOSE test_Cursor

Example:

create  Procedure [dbo].[proc_lanelistsum_initdata](@begin_date datetime,@end_date datetime)
as
declare @date datetime,--Variables used to process results  
@formatSquad varchar(50),
@v_desc varchar(500)
begin
    set @v_desc = 'Dates of export workshops processed are as follows::';
  --Declare an exit flow cursor  
  Declare curSquaddateFee Cursor for   
  select squaddate from laneexlist_id where SquadDate between @begin_date and @end_date group by squaddate  ---Query Statement (Query Current Work Class)  
   --open  
  Open curSquaddateFee   
  --Cycling and extracting records  
  Fetch Next From curSquaddateFee Into @date--Take the first record and put it in@result in  
  While ( @@Fetch_Status=0 )     
        begin  
        set @formatSquad = CONVERT(varchar(10), @date, 23);--Get the processing date
        --Delete the export summary table. The current shift is@@formatSquad Data
        delete RepLaneExListSum where squaddate = @formatSquad;
        --from laneexlist Table query summary squaddate The following data is reinserted into the summary table
        exec proc_laneexenlistSquaddate @formatSquad,2;
        --Delete the Pass Card Summary Table. The current shift is@@formatSquad Data 
        delete ys_PasscardviewSum where squaddate = @formatSquad and listtype in(2,3,4,5)
         --from laneexlist Table query summary squaddate The following data is reinserted into the summary table
        exec proc_laneexenlistSquaddate @formatSquad,4;
        set @v_desc = @v_desc + @formatSquad+',';
     Fetch Next From curSquaddateFee into @date----Next item  
       end   
  --Close the cursor     
   Close curSquaddateFee  
   insert into EXEC_PROC_LOG(id,name,[description],[status],createtime) 
   values(newid() ,'proc_lanelistsum-Processing Outlet Pipeline Summary Table Storage Procedures',@v_desc,1,GETDATE());
   set @v_desc = @v_desc + 'Dates of entry workshops are as follows:';
  --Release cursor  
   Deallocate curSquaddateFee 
 end;

Keywords: Database Java SQL

Added by g5604 on Mon, 15 Jul 2019 01:11:13 +0300