SQL Server cursor Sentence declaration/Open/Loop instance _mssql

Source: Internet
Author: User
Tags how to use sql server how to use sql
How to use SQL Server Tour banner sentences:
Copy Code code as follows:

--Declares a cursor
DECLARE MyCursor CURSOR
For the SELECT Top 5 fbookname,fbookcoding The from tbookinfo//defines a cursor called MyCursor that holds the data after the for select

--Open a cursor
Open mycursor//Opens the dataset

--Loop a cursor
DECLARE @BookName nvarchar, @BookCoding nvarchar (2000)
Fetch NEXT from MyCursor into @BookName, @BookCoding//move cursor to point to the first data, extract the first data to be stored in the variable
While @ @FETCH_STATUS =0//continue looping if the last operation succeeds
BEGIN
print ' name ' + @BookName
FETCH next from MyCursor into @BookName, @BookCoding//Continue with the next line
End

--Close cursor
Close MyCursor
--Releasing resources
Deallocate mycursor

eg
Copy Code code as follows:

CREATE TABLE #a
(
ID varchar (20),
Name varchar (20)
)
INSERT INTO #a Select 1, ' Jack '
INSERT INTO #a Select 2, ' Join '
Insert INTO #a Select 3, ' Make '
DECLARE mycursor cursor
For a SELECT * from #a
Open MyCursor
DECLARE @id varchar (@name), varchar (20)
FETCH NEXT from MyCursor into @id, @name
While @ @fetch_status =0
Begin
Select @id, @name
FETCH NEXT from MyCursor into @id, @name
End
Close MyCursor
Deallocate mycursor


Cursor is a row-level operation consumes a lot of SQL queries are based on datasets, so general queries can use datasets to use data sets do not use cursors data volume is a performance killer
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.