sql while循环

SQL WHILE loop provides us with the advantage to execute the SQL statement(s) repeatedly until the specified condition result turn out to be false.

SQL WHILE循环为我们提供了重复执行SQL语句的优势,直到指定的条件结果为假。

In the following sections of this article, we will use more flowcharts in order to explain the notions and examples. For this reason, firstly, we will explain what is a flowchart briefly. The flowchart is a visual geometric symbol that helps to explain algorithms visually. The flowchart is used to simply design and document the algorithms. In the flowchart, each geometric symbol specifies different meanings.

在本文的以下各节中,我们将使用更多流程图以解释概念和示例。 因此,首先,我们将简要解释什么是流程图。 流程图是可视的几何符号,有助于直观地解释算法。 该流程图仅用于设计和记录算法。 在流程图中,每个几何符号都有不同的含义。

The following flowchart explains the essential structure of the WHILE loop in SQL:

以下流程图说明了SQL中WHILE循环的基本结构:

As you can see, in each iteration of the loop, the defined condition is checked, and then, according to the result of the condition, the code flow is determined. If the result of the condition is true, the SQL statement will be executed. Otherwise, the code flow will exit the loop. If any SQL statement exists outside the loop, it will be executed.

如您所见,在循环的每次迭代中,都会检查定义的条件,然后根据条件的结果确定代码流。 如果条件的结果为true,则将执行SQL语句。 否则,代码流将退出循环。 如果循环外存在任何SQL语句,它将被执行。

SQL WHILE循环语法和示例 (SQL WHILE loop syntax and example)

The syntax of the WHILE loop in SQL looks like as follows:

SQL中的WHILE循环的语法如下所示:

WHILE condition
BEGIN{...statements...}
END

After these explanations, we will give a very simple example of a WHILE loop in SQL. In the example given below, the WHILE loop example will write a value of the variable ten times, and then the loop will be completed:

经过这些解释,我们将给出一个非常简单SQL WHILE循环示例。 在下面给出的示例中,WHILE循环示例将写入该变量的值十次,然后循环将完成:

DECLARE @Counter INT
SET @Counter=1
WHILE ( @Counter <= 10)
BEGINPRINT 'The counter value is = ' + CONVERT(VARCHAR,@Counter)SET @Counter  = @Counter  + 1
END

Now, we will handle the WHILE loop example line by line and examine it with details.

现在,我们将逐行处理WHILE循环示例,并对其进行详细检查。

In this part of the code, we declare a variable, and we assign an initializing value to it:

在代码的这一部分中,我们声明一个变量,并为其分配一个初始化值:

DECLARE @Counter INT
SET @Counter=1

This part of the code has a specified condition that until the variable value reaches till 10, the loop continues and executes the PRINT statement. Otherwise, the while condition will not occur, and the loop will end:

这部分代码具有指定条件,直到变量值达到10为止,循环才会继续并执行PRINT语句。 否则,while条件将不会发生,并且循环将结束:

WHILE ( @Counter <= 10)

In this last part of the code, we executed the SQL statement, and then we incremented the value of the variable:

在代码的最后一部分,我们执行了SQL语句,然后增加了变量的值:

BEGINPRINT 'The counter value is = ' + CONVERT(VARCHAR,@Counter)SET @Counter  = @Counter  + 1
END

The following flowchart illustrates this WHILE loop example visually:

以下流程图直观地说明了此WHILE循环示例:

无限SQL WHILE循环 (Infinite SQL WHILE loop )

In the infinite loop AKA endless loop, the condition result will never be false, so the loop never ends and can work forever. Imagine that we have a WHILE loop, and we don’t increment the value of the variable. In this scenario, the loop runs endlessly and never ends. Now, we will realize this scenario with the help of the following example. We need to take account of one thing that we should not forget to cancel the execution of the query manually:

在无限循环(又称为无穷循环)中,条件结果永远不会为假,因此循环永远不会结束并且可以永远工作。 想象一下,我们有一个WHILE循环,并且我们不增加变量的值。 在这种情况下,循环将无限地运行,并且永远不会结束。 现在,我们将在以下示例的帮助下实现此方案。 我们需要考虑一件事,我们不应忘记手动取消查询的执行:

DECLARE @Counter INT
SET @Counter=1
WHILE ( @Counter <= 10)
BEGINPRINT 'Somebody stops me!'END

In the following flowchart, it is obvious that the value of the variable never changes; therefore, the loop never ends. The reason for this issue is that the variable is always equal to 1 so the condition returns true for each iteration of the loop:

在下面的流程图中,很明显,变量的值从不改变。 因此,循环永远不会结束。 出现此问题的原因是,变量始终等于1,因此条件对于循环的每次迭代都返回true:

BREAK声明 (BREAK statement )

BREAK statement is used in the SQL WHILE loop in order to exit the current iteration of the loop immediately when certain conditions occur. In the generally IF…ELSE statement is used to check whether the condition has occurred or not. Refer to the SQL IF Statement introduction and overview article for more details about the IF…ELSE statement.

在SQL WHILE循环中使用BREAK语句,以便在发生某些情况时立即退出循环的当前迭代。 通常在IF…ELSE语句中使用该语句检查条件是否发生。 有关IF…ELSE语句的更多详细信息,请参见SQL IF语句介绍和概述文章。

The following example shows the usage of the BREAK statement in the WHILE loop:

以下示例显示了WHILE循环中BREAK语句的用法:

DECLARE @Counter INT
SET @Counter=1
WHILE ( @Counter <= 10)
BEGINPRINT 'The counter value is = ' + CONVERT(VARCHAR,@Counter)IF @Counter >=7BEGINBREAKENDSET @Counter  = @Counter  + 1
END

In this example, we have checked the value of the variable, and when the value is equal or greater than 7, the code entered the IF…ELSE block and executed the BREAK statement, and so it exited the loop immediately. For this reason, the message shows the values of the variable up to 7. If the condition of the IF…ELSE statement does not meet, the loop will run until the condition result will be false. The following flowchart explains the working logic of the BREAK statement example as visually:

在此示例中,我们检查了变量的值,当该值等于或大于7时,代码进入IF…ELSE块并执行BREAK语句,因此它立即退出循环。 因此,该消息显示变量的值最多为7。如果IF…ELSE语句的条件不满足,则循环将运行,直到条件结果为false。 下面的流程图从视觉上解释了BREAK语句示例的工作逻辑:

继续声明 (CONTINUE statement )

CONTINUE statement is used in the SQL WHILE loop in order to stop the current iteration of the loop when certain conditions occur, and then it starts a new iteration from the beginning of the loop. Assume that we want to write only even numbers in a WHILE loop. In order to overcome this issue, we can use the CONTINUE statement. In the following example, we will check whether the variable value is odd or even. If the variable value is odd, the code enters the IF…ELSE statement blocks and increment the value of the variable, execute the CONTINUE statement and starts a new iteration:

为了在某​​些情况发生时停止循环的当前迭代,在SQL WHILE循环中使用了CONTINUE语句,然后从循环的开头开始了新的迭代。 假设我们只想在WHILE循环中只写偶数。 为了克服这个问题,我们可以使用CONTINUE 声明。 在下面的示例中,我们将检查变量值是奇数还是偶数。 如果变量值是奇数,则代码进入IF…ELSE语句块并递增变量的值,然后执行CONTINUE 语句并开始新的迭代:

DECLARE @Counter INT
SET @Counter=1
WHILE ( @Counter <= 20)
BEGINIF @Counter % 2 =1BEGINSET @Counter  = @Counter  + 1CONTINUEENDPRINT 'The counter value is = ' + CONVERT(VARCHAR,@Counter)SET @Counter  = @Counter  + 1
END

The following flowchart explains the working logic of the CONTINUE statement example as visually:

以下流程图从视觉上解释了CONTINUE语句示例的工作逻辑:

通过WHILE循环读取表记录 (Reading table records through the WHILE loop)

In the following example, we will read table data, row by row. Firstly we will create a sample table:

在下面的示例中,我们将逐行读取表数据。 首先,我们将创建一个示例表:

USE tempdb
GO
DROP TABLE IF EXISTS SampleTable
CREATE TABLE SampleTable
(Id INT, CountryName NVARCHAR(100), ReadStatus TINYINT)
GO
INSERT INTO SampleTable ( Id, CountryName, ReadStatus)
Values (1, 'Germany', 0),(2, 'France', 0),(3, 'Italy', 0),(4, 'Netherlands', 0) ,(5, 'Poland', 0)SELECT * FROM SampleTable

In this step, we will read all data row by row with the help of the WHILE loop:

在这一步中,我们将借助WHILE循环逐行读取所有数据:

USE tempdb
GODECLARE @Counter INT , @MaxId INT, @CountryName NVARCHAR(100)
SELECT @Counter = min(Id) , @MaxId = max(Id)
FROM SampleTableWHILE(@Counter IS NOT NULLAND @Counter <= @MaxId)
BEGINSELECT @CountryName = CountryNameFROM SampleTable WHERE Id = @CounterPRINT CONVERT(VARCHAR,@Counter) + '. country name is ' + @CountryName  SET @Counter  = @Counter  + 1
END

In this example, we read the table rows via the WHILE loop. We can also develop more sophisticated and advanced loops based on our needs.

在此示例中,我们通过WHILE循环读取表行。 我们还可以根据需要开发更复杂和更高级的循环。

结论 (Conclusion)

In this article, we learned the SQL WHILE loop with quite simple examples. We also virtualized and explained the examples with flowcharts. WHILE loop helps us to achieve iterative operations in SQL Server. At the same time, BREAK and CONTINUE statements can be used to control iteration of the WHILE loop in SQL Server.

在本文中,我们通过非常简单的示例学习了SQL WHILE循环。 我们还通过流程图虚拟化并说明了示例。 WHILE循环可帮助我们在SQL Server中实现迭代操作。 同时,BREAK和CONTINUE语句可用于控制SQL Server中WHILE循环的迭代。

翻译自: https://www.sqlshack.com/sql-while-loop-with-simple-examples/

sql while循环

sql while循环_SQL WHILE循环的简单示例相关推荐

  1. sql中的while循环_SQL While循环:了解SQL Server中的While循环

    sql中的while循环 The SQL While loop is used to repeatedly execute a certain piece of SQL script. SQL Whi ...

  2. sql as关键字_SQL AS关键字概述和示例

    sql as关键字 SQL AS keyword is used to give an alias to table or column names in the queries. In this w ...

  3. sql limit 子句_SQL按子句概述和示例

    sql limit 子句 This article will cover the SQL ORDER BY clause including syntax, usage scenarios to so ...

  4. java循环左一_java实现循环左移和右移的简单算法

    java实现循环左移和右移的简单算法 byte a=112,用程序实现,将其循环左移三位和右移三位. 112的二进制原码:0111 0000 112循环左移3位后的二进制码:1000 0011 112 ...

  5. SQL 中循环、for循环、游标

    我们使用SQL语句处理数据时,可能会碰到一些需要循环遍历某个表并对其进行相应的操作(添加.修改.删除),这时我们就需要用到咱们在编程中常常用的for或foreach,但是在SQL中写循环往往显得那么吃 ...

  6. sql脚本语言中的循环语句介绍

    sql脚本语言中的循环语句介绍 –sql脚本语言的循环介绍: –1.goto循环点. declare x number; begin x:=0;–变量初始化: <<repeat_loop& ...

  7. part4-2 流程控制二(循环结构,while、for循环,列表推导式、生成器推导式,常用工具函数,控制循环结构,4个简单实例)...

    循环语句在循环条件满足时,可反复执行某一段代码,这段被重复执行的代码称为循环体.在循环体中,需要在合适的时候把循环条件设置为假,从而结束循环:否则循环一直执行下去形成死循环.循环语句通常包含如下4个部 ...

  8. php循环checkbox,php循环删除checkbox | 学步园

    一.首先要了解sql语句$SQL=delete from `user` where id in (1,2,4); 表单大概是:form action= method=post input name=I ...

  9. 使用控制结构——循环语句——基本循环

    在pl/sql中最简单的循环语句时基本循环语句,这种循环语句以loop开始,以endloop结束, 注意,当编写基本循环时,一定要包含exit 语句,否则pl/sql 快会陷入死循环:另外,当使用基本 ...

最新文章

  1. 报错解决:InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got
  2. Tensorflow遇到的问题InvalidArgumentError: Graph execution error:2 root error(s) found.解决方法
  3. 读懂这篇文章,你的阿里技术面就可以过关了 | Apache RocketMQ 101
  4. CPU 和 GPU频率设置
  5. quartz.net隔一天执行一次_一天拉几次大便算正常?啥时候拉最好?关于便便的事,可算明白了...
  6. X64-CL iPro 采集卡OC-64EO-IPRO0简介
  7. 【三支火把】--- 关于UEFIPCD的总结介绍
  8. Android vs iOS vs BlackBerry: Which is the most secure holiday gift?
  9. [ios] 申请账号,发布应用
  10. notepad 快速新建html,notepad编写html
  11. 金融网络直播室软件的功能介绍
  12. 在Windows环境下,将tomcat的默认端口修改为8081
  13. 手把手教你搭建docker环境
  14. android studio项目中将普通文件夹变成moudle
  15. 安全远程办公的十大技巧
  16. ORACLE 体系结构详细图
  17. 如何写一个好的缺陷,大牛都是这样的做的
  18. java的博_小博老师解析Java核心技术 ——I/O流
  19. DNS 学习笔记之三- 详解DNS的资源记录
  20. 只用听的计算机课程录音,录制网络课程如何录声音?其实这个方法更简单

热门文章

  1. Android界面性能优化最全总结、原理剖析
  2. 庆祝本人在cnblogs排名进入前2000!
  3. cacti监控服务器
  4. [Alpha阶段]第二次Scrum Meeting
  5. 剑指offer.数值的整数次方
  6. Linux笔记(开机自动将kerne log保存到SD卡中)
  7. 网页常用分享代码大全——整理摘抄至他人嘿嘿
  8. 通过rss阅读器写blog
  9. LeetCode(235)——二叉搜索树的最近公共祖先(JavaScript)
  10. SyntaxError: await is only valid in async function