SQL Cursor Basic usage [with two fetch NEXT from into statement?]

Source: Internet
Author: User

Code highlighting produced byActipro codehighlighter (freeware) http://Www.CodeHighlighter.com/--> 1 table1 structure as followsIdintnamevarchar( -)Declare @id intDeclare @name varchar( -)DeclareCursor1cursor  for         --Defining Cursors Cursor1Select *  fromTable1--objects using cursors (fill in select text as required)OpenCursor1--Open CursorFetch Next  fromCursor1 into @id,@name  --move the cursor down by 1 rows to get the data into the previously defined variable @id, @name while @ @fetch_status=0           --determine if the data was successfully obtainedbeginUpdateTable1SetName=Name+'1'whereId=@id                           --Handle it accordingly (fill in the SQL text as needed)Fetch Next  fromCursor1 into @id,@name  --move the cursor down by 1 rowsEndCloseCursor1--Close CursorsdeallocateCursor1

Cursor General format:
DECLARE cursor name cursor for SELECT field 1, Field 2, Field 3,... From table name WHERE ...
OPEN cursor Name
FETCH NEXT from cursor name into variable name 1, variable name 2, variable name 3,...
While @ @FETCH_STATUS =0
BEGIN
SQL statement Execution process ...
FETCH NEXT from cursor name into variable name 1, variable name 2, variable name 3,...
END
CLOSE cursor Name
DEALLOCATE cursor name (delete cursor)

Note: The "fetch next from" is used two times because the first time is only used to judge the @ @FETCH_STATUS, the next "fetch next from" is the loop used! That is, the following is a repeated execution between the BEGIN end. Read one line at a time!

SQL Cursor Basic usage [with two fetch NEXT from into statement?]

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.