转至繁体中文版     | 网站首页 | 图文教程 | 资源下载 | 站长博客 | 图片素材 | 武汉seo | 武汉网站优化 | 
最新公告:     敏韬网|教学资源学习资料永久免费分享站!  [mintao  2008年9月2日]        
您现在的位置: 学习笔记 >> 图文教程 >> 数据库 >> Sql Server >> 正文
Building a T-SQL Loop         

Building a T-SQL Loop

作者:闵涛 文章来源:闵涛的学习笔记 点击数:2757 更新时间:2007/11/14 12:55:46
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 Categor

[1] [2]  下一页


[办公软件]Word表格中Shift+Alt+方向键的妙用  [系统软件]A REVIEW OF SQLEXPLORER PLUG-IN
[VB.NET程序]Read a string at a given address  [VB.NET程序]Read a byte, integer or long from memory
[Delphi程序]// I have a comment ----Delphi 研发人员谈注释 …  [Delphi程序]// I have a comment  ----Delphi 研发人员谈注释
[Delphi程序]Creating a real singleton class in Delphi 5  [Delphi程序]Download a file from a FTP Server
[Delphi程序]Building ActiveX Controls with Delphi 3  [Delphi程序]2004.11.29.Starting a Project
教程录入:mintao    责任编辑:mintao 
  • 上一篇教程:

  • 下一篇教程:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
      注:本站部分文章源于互联网,版权归原作者所有!如有侵权,请原作者与本站联系,本站将立即删除! 本站文章除特别注明外均可转载,但需注明出处! [MinTao学以致用网]
      网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)

    同类栏目
    · Sql Server  · MySql
    · Access  · ORACLE
    · SyBase  · 其他
    更多内容
    热门推荐 更多内容
  • 没有教程
  • 赞助链接
    更多内容
    闵涛博文 更多关于武汉SEO的内容
    500 - 内部服务器错误。

    500 - 内部服务器错误。

    您查找的资源存在问题,因而无法显示。

    | 设为首页 |加入收藏 | 联系站长 | 友情链接 | 版权申明 | 广告服务
    MinTao学以致用网

    Copyright @ 2007-2012 敏韬网(敏而好学,文韬武略--MinTao.Net)(学习笔记) Inc All Rights Reserved.
    闵涛 投放广告、内容合作请Q我! E_mail:admin@mintao.net(欢迎提供学习资源)

    站长:MinTao ICP备案号:鄂ICP备11006601号-18

    闵涛站盟:医药大全-武穴网A打造BCD……
    咸宁网络警察报警平台