How to traverse a result set and use Transact-SQL in SQL Server

Source: Internet
Author: User
Loop result sets using Transact-SQL statements

You can use three methods to cycle a result set by using a Transact-SQL statement.

One way is to useTemporaryTable. Using this method, you create a "snapshot" of the initial SELECT statement and use it as the basic "Pointer ". For example:
/********** Example 1 ***********/declare @ au_idChar(11)

SetRowcount0
Select* Into # mytempFromAuthors

SetRowcount1

Select@ Au_id = au_idFrom# Mytemp

While@ Rowcount <>0
Begin
SetRowcount0
Select*From# MytempWhereAu_id = @ au_id
Delete # mytempWhereAu_id = @ au_id

SetRowcount1
Select@ Au_id = au_idFrom# Mytemp <br/>
End
SetRowcount0

The second method is to useMinFunction. After this method is captured, the stored procedure starts to run. Assume that the new row has a unique identifier greater than the new row being processed in the query. For example:
/************ Example 2 ************/declare @ au_idChar(11)

Select@ Au_id = min (au_id)FromAuthors

while @ au_id is not null
begin
select * from authors where au_id = @ au_id
select @ au_id = min (au_id) from authors where au_id> @ au_id
end


Remarks
: Example 1 and Example 2 assume that a unique identifier exists for each row in the source table. In some cases, there may be no unique identifier. In this case, you can modify the key columns to be created.TemporaryTable method. For example:
/********** Example 3 **********/SetRowcount0
SelectNull mykey, * into # mytempFromAuthors

SetRowcount1
Update # mytempSetMykey =1

While @ Rowcount> 0
Begin
Set Rowcount 0
Select * From # Mytemp Where Mykey = 1
Delete # mytemp Where Mykey = 1
Set Rowcount 1
Update # mytemp Set Mykey = 1
End
Set Rowcount 0

Original article: http://www.cnblogs.com/sskset/archive/2008/07/14/1242094.html

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.