Principle of SQL Server database cursor

Source: Internet
Author: User
Principle of cursor

In general, SQL query results are results set of multiple records, while advanced languages can only process one record at a time. The cursor mechanism is used to read and process multiple records at a time. In this way, the operation on the set is converted to the processing of a single record. The procedure for using a cursor is as follows:

1. Declare the cursor. The SELECT statement is not executed when the cursor is declared.
Declare <cursor Name> cursor for <SELECT statement>;
 
2. Open the cursor. When you open a cursor, you actually execute the corresponding SELECT statement to read the query results to the buffer zone. At this time, the cursor is active and the Pointer Points to the first record of the query result set.
Open <cursor Name>;
 
3. Push the cursor pointer and read the current record. Use the fetch statement to forward the cursor pointer to a record and read the current record in the buffer to the variable. The fetch statement is usually used in a cyclic structure. The fetch statement is executed cyclically to retrieve rows in the result set one by one for processing. In many databases, the cursor pointer can be moved at any step, not just forward the cursor pointer to a row.
Fetch <cursor Name> into <variable 1>, <variable 2>...
 
4. Close the cursor. Close the cursor with the close statement to release the buffer and other resources occupied by the result set. When the cursor is closed, it is no longer associated with the original query result set. However, the cursor can be opened again, which is associated with the new query results.
Close <cursor Name>;

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.