SQL Server Cursors use

Source: Internet
Author: User

1. Declaring cursors
DECLARE cursor name CURSOR SELECT statement (NOTE: This must be a SELECT statement)
2. Open the cursor
OPEN cursor Name
3. Reading cursor data
Fetch [Next | Prior | First | Last | Absolute N | Relative N] from cursor name into @name1, @name2 ...
while (@ @FETCH_STATUS = 0)
BEGIN
--The SQL statement to execute
FETCH NEXT from cursor name
END

4. Close the cursor
The CLOSE cursor name. The cursor cannot be read after closing, but can be opened again using the Open statement
5. Releasing cursors
The DEALLOCATE cursor name. Delete cursor, no longer available

Example:

Declare @index int;Declare @userId uniqueidentifier;Set @index=1;DeclareUser_curcursor  for SelectUserid fromT_userOrder  byCreatetimedescOpenUser_curFetch Next  fromUser_cur into @userId while(@ @FETCH_STATUS=0)begin  UpdateT_userSetSort=@index whereUserid=@userId; Set @index=@index+1; Fetch Next  fromUser_cur into @userIdEndCloseuser_cur;deallocateUser_cur;

Reference Link: http://www.cnblogs.com/youngberry/archive/2009/07/17/1525647.html

SQL Server Cursors use

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.