The following is the most direct way to use a cursor:
Code running condition: A tb_paperinfo (paperid, papername) Table
-- Declare a cursor marked as C. The cursor identifies two columns from the tb_paperinfo table.
Declare C cursor for select top 3 paperid, papername from tb_paperinfo
-- Open the cursor C
Open c
-- Declare two variables to temporarily store the values of corresponding fields
Declare @ paperid varchar (20 );
Declare @ papername varchar (20 );
-- @ Fetch_status: The cursor location returned to identify whether the cursor has reached the end or whether it is still on or off
-- When fetch next from C is not executed, @ fetch_status is-1
Fetch next from C into @ paperid, @ papername ---- note: the number of variables after into corresponds to the number of columns in the SELECT statement. After executing this statement, @ fetch_status returns 0.
Declare @ I int;
Set @ I = 1;
While @ fetch_status = 0
Begin
/** // * Here, you can use the @ paperid and @ papername variables to do what you want */
Print 'quarter '+ Cast (@ I as varchar (20) + 'record paperid:' + @ paperid
Print 'quarter '+ Cast (@ I as varchar (20) + 'record papername:' + @ papername
-- Use the fetch next from statement to retrieve the next record
Fetch next from C into @ paperid, @ papername
Set @ I = @ I + 1;
End
-- Close the cursor. If you want to use it again, you can use the open method to open it again (open before release)
Close C
-- Release cursor
Deallocate C