在 T-SQL 中具有多个条件的 while 循环

While loop with multiple conditions in T-SQL(在 T-SQL 中具有多个条件的 while 循环)
本文介绍了在 T-SQL 中具有多个条件的 while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

首先让我说我知道我知道这种循环很可怕,你不应该在 Transact SQL 中使用它们.但是,出于某些目的(这些目的无关紧要,所以不要问我你想做什么!?")你只需要这样做.我不想,但我必须.

Let me start out by saying I know I KNOW that these kind of loops are horrible and you shouldn't use them in Transact SQL. But, for some purposes (those purposes being irrelevant so don't ask me "what're you trying to do!?") ya just have to. I don't want to, but I gotta.

无论如何.有没有办法让 T-SQL 中的 while 循环在复杂的条件语句上终止?就像,在 C# 中,我只想说 while (i > -10 && i <10) ,因为我希望循环在标记值介于 -10 和 10 之间时终止,但我只是...可以不知道怎么做.

Anyway. Is there some way to have a while loop in T-SQL terminate on a complex conditional statement? like, in C# I'd just say while (i > -10 && i < 10) , because I want the loop to terminate when the sentinel value is between -10 and 10, but I just... can't figure out how to do it.

这可能非常简单……或者……不可能.请指教.

It's probably excruciatingly simple... or.. impossible. Please advise.

现在,我刚刚得到

WHILE @N <> 0
BEGIN
   --code and such here
END

推荐答案

你必须看WHILE语句的声明:

You must look at declaration of WHILE statement:

WHILE Boolean_expression 
     { sql_statement | statement_block | BREAK | CONTINUE } 

首先,你可以像 Dan 所说的那样使用复杂的 Boolean_expression:

First of all you can use complex Boolean_expression as Dan said:

WHILE @N > -1 AND @N <10
BEGIN
END

如果您想为代码添加更多灵活性,可以使用 IF 与 BREAK,类似这样:

If you want to add more flexibility to you code you can use IF with BREAK, something like this:

WHILE @N > -1 AND @N <10
BEGIN

  -- code
  IF (SELECT MAX(ListPrice) FROM Production.Product) > $500
    BREAK
  END
  -- code

END

退出循环或使用 CONTINUE 跳过一个循环.

to go out of cycle or use CONTINUE to skip one cycle.

这篇关于在 T-SQL 中具有多个条件的 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)