分享
 
 
 

Building a T-SQL Loop

王朝mssql·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

November 5, 2003

T-SQL Programming Part 2 - Building a T-SQL Loop

By Gregory A. Larsen

This is the second article in my T-SQL programming series. This article will discuss building a program loop using T-SQL. In addition to talking about building a loop, I will also discuss ways of controlling the loop processing, and different methods to break out of a loop.

A programming loop is a chunk of code that is executed over and over again. In the loop some logic is executed repeatedly in an iterative fashion until some condition is met that allows the code to break out of the loop. One example of where you might use a loop would be to process through a set of records one record at a time. Another example might be where you need to generate some test data and a loop would allow you to insert a record into your test data table with slightly different column values, each time the loop is executed. In this article I will discuss the WHILE, BREAK, CONTINUE, and GOTO statements.

WHILE Statement

In T-SQL the WHILE statement is the most commonly used way to execute a loop. Here is the basic syntax for a WHILE loop:

WHILE <Boolean expression> <code block>

Where a <Boolean expression> is any expression that equates to a true or false answer, and the <code block> is the desire code to be executed while the <Boolean expression> is true. Let's go through a real simple example.

In this example I will increment a counter from 1 to 10 and display the counter each time through the WHILE loop.

declare @counter int

set @counter = 0

while @counter < 10

begin

set @counter = @counter + 1

print 'The counter is ' + cast(@counter as char)

end

Here the code executes the WHILE statement as long as the @counter integer variable is less than 10, this is the Boolean expression of the WHILE loop. The @counter variable starts out at zero, and each time through the WHILE loop it is incremented by 1. The PRINT statement displays the value in the @counter variable each time through the WHILE loop. The output from this sample looks like this:

The counter is 1

The counter is 2

The counter is 3

The counter is 4

The counter is 5

The counter is 6

The counter is 7

The counter is 8

The counter is 9

The counter is 10

As you can see, once the @counter variable reaches 10 the Boolean expression that is controlling the WHILE loop is no longer true, so the code within the while loop is no longer executed.

Not only can you have a single while loop, but you can have WHILE loops inside WHILE loops. Or commonly know as nesting of WHILE loops. There are lots of different uses where nesting is valuable. I commonly use nesting of WHILE loops to generate test data. My next example will use the WHILE loop to generate test records for a PART table. A given PART record is uniquely identified by a Part_Id, and a Category_Id. For each Part_Id there are three different Category_Id's. Here is my example that generates 6 unique records for my PART table using a nested WHILE loop.

declare @Part_Id int

declare @Category_Id int

declare @Desc varchar(50)

create table PART (Part_Id int, Category_Id int, Description varchar(50))

set @Part_Id = 0

set @Category_Id = 0

while @Part_Id < 2

begin

set @Part_Id = @Part_Id + 1

while @Category_Id < 3

begin

set @Category_Id = @Category_Id + 1

set @Desc = 'Part_Id is ' + cast(@Part_Id as char(1)) +

' Category_Id ' + cast(@Category_Id as char(1))

insert into PART values(@Part_Id,

@Category_Id,

@Desc )

end

set @Category_Id = 0

end

select * from PART

drop table PART

Here is the output from the SELECT statement at the bottom of this nested WHILE loop example.

Part_Id Category_Id Description

----------- ----------- -----------------------------------------

1 1 Part_Id is 1 Category_Id 1

1 2 Part_Id is 1 Category_Id 2

1 3 Part_Id is 1 Category_Id 3

2 1 Part_Id is 2 Category_Id 1

2 2 Part_Id is 2 Category_Id 2

2 3 Part_Id is 2 Category_Id 3

As you can see, by using a nested WHILE loop each combination of Part_Id and Category_Id is unique. The code within the first WHILE loop controlled the incrementing of the Part_Id, where as the second WHILE loop set the Category_Id to a different value each time through the loop. The code within the first while loop was executed only twice, but the code inside the second WHILE loop was executed 6 times. Thus giving me 6 sample PART records.

BREAK and CONTINUE Statements

Now sometimes you want to build a loop that will process through logically to the end most of the time, but not all the time. In other words, you may want to break out of the loop if some particular condition arises. Also in addition to breaking out of the loop, you may not want to process all the code in the loop before going back to the top of the loop and starting through the next iteration of the loop. For these kinds of programming requirements SQL Server provides the BREAK and CONTINUE statements.

The BREAK statement exits out of the inner most WHILE loop, and proceeds to the statement following the END statement that is associated with the loop in which the BREAK statement is executed. The CONTINUE statement skips executing the rest of the statements between the CONTINUE statement and the END statement of the current loop and starts executing at the first line following the BEGIN statement of the current WHILE loop. Let's go though a couple of BREAK and CONTINUE examples.

For the BREAK statement I'm going to modify my last example that generated PART table records. This time I'm going to BREAK out of the inner WHILE loop when Category_ID is 2 and PART_ID is 1. Here is my code for the BREAK statement.

declare @Part_Id int

declare @Category_Id int

declare @Desc varchar(50)

create table PART (Part_Id int, Category_Id int, Description varchar(50))

set @Part_Id = 0

set @Category_Id = 0

while @Part_Id < 2

begin

set @Part_Id = @Part_Id + 1

while @Category_Id < 3

begin

set @Category_Id = @Category_Id + 1

If @Category_ID = 2 and @Part_ID = 1

Break

set @Desc = 'Part_Id is ' + cast(@Part_Id as char(1)) +

' Category_Id ' + cast(@Category_Id as char(1))

insert into PART values(@Part_Id,

@Category_Id,

@Desc )

end

set @Category_Id = 0

end

select * from PART

drop table PART

Here is the output for this code that contains a BREAK statement inside the inner WHILE loop.

Part_Id Category_Id Description

----------- ----------- -----------------------------------------

1 1 Part_Id is 1 Category_Id 1

2 1 Part_Id is 2 Category_Id 1

2 2 Part_Id is 2 Category_Id 2

2 3 Part_Id is 2 Category_Id 3

From this output you can see that no records were inserted for Part_Id = 1 and Category_Id =2 or 3, where as there are records for Part_Id = 2 with all values for the Category_Id column. This is because the IF statement in the inner loop forced the BREAK statement to exit the inner loop. Since there were records generate for Part_Id = 2, shows that the BREAK statement only exited the inner loop and not the outer loop.

Now just to stay with the same example I've been using, let's replace the BREAK statement in the code above with a CONTINUE statement. Here is the code for demonstrating the CONTINUE statement.

declare @Part_Id int

declare @Category_Id int

declare @Desc varchar(50)

create table PART (Part_Id int, Category_Id int, Description varchar(50))

set @Part_Id = 0

set @Category_Id = 0

while @Part_Id < 2

begin

set @Part_Id = @Part_Id + 1

while @Category_Id < 3

begin

set @Category_Id = @Category_Id + 1

If @Category_ID = 2 and @Part_ID = 1

Continue

set @Desc = 'Part_Id is ' + cast(@Part_Id as char(1)) +

' Category_Id ' + cast(@Category_Id as char(1))

insert into PART values(@Part_Id,

@Category_Id,

@Desc )

end

set @Category_Id = 0

end

select * from PART

drop table PART

When you use the CONTINUE statement you get the following output.

----------- ----------- -----------------------------------------

1 1 Part_Id is 1 Category_Id 1

1 3 Part_Id is 1 Category_Id 3

2 1 Part_Id is 2 Category_Id 1

2 2 Part_Id is 2 Category_Id 2

2 3 Part_Id is 2 Category_Id 3

As you can see, when I use the CONTINUE statement only the record with Category_Id = 2 and Part_Id = 1 is missing. This is because the CONTINUE statement does not break out of the inner WHILE loop but only goes back to the top of the WHILE loop without inserting the record. This happens only when Category_Id is 2 and Part_Id is equal to 1. When Part_Id = 1 and Category_Id = 3 the insert statement is still executed.

GOTO Statement

The BREAK statement will only exit you from the currently processing WHILE loop, it will not break out of all WHILE loops. However, occasionally this is the kind of functionality your T-SQL script needs. To have your code break out of all WHILE loops, no matter how many nested WHILE statements you have, you will need to use the GOTO statement. Now I know most programmers cringe at the thought of using the GOTO statement, but in this case I feel the GOTO is an except able practice. Using my same example I will use the GOTO to break out of both WHILE loops, when the PART_Id = 1 and the Category_ID=3.

declare @Part_Id int

declare @Category_Id int

declare @Desc varchar(50)

create table PART (Part_Id int, Category_Id int, Description varchar(50))

set @Part_Id = 0

set @Category_Id = 0

while @Part_Id < 2

begin

set @Part_Id = @Part_Id + 1

while @Category_Id < 3

begin

set @Category_Id = @Category_Id + 1

If @Category_ID = 3 and @Part_ID = 1

GOTO BREAK_OUT

set @Desc = 'Part_Id is ' + cast(@Part_Id as char(1)) +

' Category_Id ' + cast(@Category_Id as char(1))

insert into PART values(@Part_Id,

@Category_Id,

@Desc )

end

set @Category_Id = 0

end

BREAK_OUT:

select * from PART

drop table PART

Here is the output from this GOTO code:

Part_Id Category_Id Description

----------- ----------- -----------------------------------------

1 1 Part_Id is 1 Category_Id 1

1 2 Part_Id is 1 Category_Id 2

Here the GOTO logic stopped the insertion of records into the PART table when @Category_ID = 3 and @Part_Id = 1. This is done by executing the "GOTO BREAKOUT" statement. Note that when this GOTO statement was executed it branched to the label "BREAK OUT:" which can be found following the END statement for the first, outer most WHILE statement.

Conclusion

Hopefully now you have a better idea of how to code a T-SQL WHILE loop. I've explained how to control the WHILE loop, break out of a loop by using the BREAK statement, use the CONTINUE statement to skip some of the code in the while loop, and/or break out of all WHILE loops using the GOTO statement. The techniques I've described should give you the basis for building all your WHILE statements from a single WHILE loop to a complex set of nested WHILE loops. My next article in this series will discuss how to process through a set of records.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有