SQL Server cursor Quick Start

Source: Internet
Author: User

There are four basic steps to use a cursor: declare the cursor, open the cursor, extract data, and close the cursor..

As shown in the following SQL example:

 

-- ========================================================== =====
-- Author: <fighting boat>
-- Create Date: <2011-04-19>
-- Description: <SQL Server cursor demo>
-- ========================================================== =====

-- Temporary table
Create   Table # Temptb
(
ID Int   Identity ,
Cola Varchar ( 50 ),
COLB Varchar ( 50 )
)
Declare   @ I   Int = 0 ;
While ( @ I < 10 )
Begin
Insert   Into # Temptb
(Cola, COLB)
Values (
' Test Field cola ' + Cast ( @ I   As   Varchar ( 10 ))
,
' Test Field COLB ' + Cast ( @ I   As   Varchar ( 10 ))
)
Set   @ I = @ I + 1 ;
End
-- Select   *   From # Temptb;

-- Define three variables to receive the cursor traversal values.
Declare   @   Varchar ( 50 ),
@ B   Varchar ( 50 ),
@ C   Varchar ( 50 );

-- Declare the cursor and fill in the data
Declare Cur Cursor   For   Select   *   From # Temptb
-- Open cursor
Open Cur
-- Fill in the next Data Entry
Fetch   Next   From Cur Into   @ , @ B , @ C
Select   @ , @ B , @ C ;
-- @ Fetch_status | 0 indicates that the extraction is successful. 1 indicates that the statement fails or the row is not in the result set. 2. The extracted row does not exist.
While ( @ Fetch_status = 0 )
Begin
-- To do something //
Fetch   Next   From Cur Into   @ , @ B , @ C ;
Select   @ , @ B , @ C ;
End
-- Close cursor
Close Cur
-- Delete a cursor Resource
Deallocate Cur

Drop Table# Temptb;

 

 

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.