Use of SQL Server cursors

Source: Internet
Author: User

DECLARE @Id NVARCHAR(MAX) DECLARE @UserName NVARCHAR(MAX)  DECLARE @Password NVARCHAR(MAX) DECLARE @NickName NVARCHAR(MAX)  Create Table#tmp (IdNVARCHAR(MAX), UserNameNVARCHAR(MAX), PasswordNVARCHAR(MAX), nicknameNVARCHAR(MAX))--Create a temporary data table--declares that the number of parameters in a cursor Mycursor,select statement must be the same as the variable name taken from the cursorDECLAREMyCursorCURSOR   for      SELECTId,username,password,nickname fromdbo. UsersOPENMyCursor--Open Cursor--extract the data from Grandperi to the variable we just declared (moving the cursor to the first data, extracting the first piece of data in the variable)FETCH NEXT  fromMyCursor into @Id,@UserName,@Password,@NickName        --determining the state of a cursor--0 FETCH statement succeeded---1 Fetch statement failed or row not in result set---2 rows that were fetched do not exist while(@ @fetch_status = 0)--if the last operation succeeds, the loop continues    BEGIN                --shows the value we take out each time we use a cursor.        --Print (@Id + '--------' [email protected]+ '--------' [email protected]+ '----' [email protected]        --Conditional Judgment        if(@Id>=Ten)        begin            INSERT  into#tmp (Id,username,password,nickname)VALUES(@Id,@UserName,@Password,@NickName)         End        --use a cursor to remove a record (continue to remove a row of data)        FETCH NEXT  fromMyCursor into @Id,@UserName,@Password,@NickName       END  CLOSEMyCursor--Close CursorsdeallocateMyCursor--undoing cursors (freeing resources)SELECT *  from#tmp;--Querying temporary tablesDROP TABLE#tmp--Delete temporary table 

Use of SQL Server cursors

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.