SQL Server Advanced Features

Source: Internet
Author: User
Tags first row

1. Cursors

Purpose: In the case of a lot of data, if the Java code in the loop after the update data, will cause frequent database connection, cost performance, so you can use the cursor

Role: Queries come out of the collection directly in SQL to traverse the update

DECLAREAllunitsCURSOR//define a cursor, and for the following is a set of cursors that you define for that collection.          for(SELECTId,code fromTbl_unitwhereTbl_unit. Parent_unit_code is NULL)        OPENallunits //Open cursor Declare @ID int,@CODE nvarchar( -) //define the variables you want to use in the cursor, it is important to note that the number of variables here must match the number of queries in the collection above you  .FETCH NEXT  fromAllunits into @ID,@CODE //Opening first row of data, importing parameters          while @ @FETCH_STATUS = 0//Determine whether the next data exists for the cursor: =0 indicates success, = 1 indicates failure or not in the result set, = 2 indicates that the fetched row does not exist.         BEGIN//Start business logic            PRINT @CODE            PRINT @ID                UPDATETbl_unitSETTbl_unit.parent_unit_code= (                    ISNULL(                        (SELECTCODE fromTbl_unitWHERETbl_unit. CODE=  Left(@CODE,6)+' the'   andId!= @ID),                        (SELECTCODE fromTbl_unitWHERETbl_unit. CODE=  Left(@CODE,3)+'000000'   andId!= @ID)                    )                )    WHERETbl_unit.id= @ID        FETCH NEXT  fromAllunits into @ID,@CODE //Import the next row of data         End//cursor ends        CLOSEallunits //close cursors deallocateAllunits//Release cursors

SQL Server Advanced Features

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.