Usage example of the midstream mark in SQL Server 2000 [ZT]

Source: Internet
Author: User
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 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 position of the returned cursor 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: At this time, the number of variables after into corresponds to the number of columns in the SELECT statement. After this statement is executed, @ 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   ' The ' +   Cast ( @ I   As Varchar ( 20 )) + ' Paperid of a record: '   + @ Paperid
Print   ' The ' +   Cast ( @ I   As Varchar ( 20 )) + ' Papername of a record: '   + @ 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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.