简体   繁体   English

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

[英]While loop with multiple conditions in T-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. 首先,我要说的是,我知道我知道这类循环很可怕,您不应该在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. 我不想,但是我得。

Anyway. 无论如何。 Is there some way to have a while loop in T-SQL terminate on a complex conditional statement? 有什么方法可以使T-SQL中的while循环终止于复杂的条件语句? 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. 例如,在C#中,我只是说while(i> -10 && i <10),因为我希望循环在哨兵值介于-10和10之间时终止,但我只是...无法弄清楚怎么做。

It's probably excruciatingly simple... or.. impossible. 这可能非常简单...或..不可能。 Please advise. 请指教。

Right now, I've just got 现在,我刚刚

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

You must look at declaration of WHILE statement: 您必须查看WHILE语句的声明:

WHILE Boolean_expression 
     { sql_statement | statement_block | BREAK | CONTINUE } 

First of all you can use complex Boolean_expression as Dan said: 首先,您可以使用复杂的Boolean_expression,如Dan所说:

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

If you want to add more flexibility to you code you can use IF with BREAK, something like this: 如果要为代码增加灵活性,可以将IF与BREAK结合使用,如下所示:

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

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

END

to go out of cycle or use CONTINUE to skip one cycle. 退出循环或使用CONTINUE跳过一个循环。

I feel like a complete idiot. 我觉得自己是个白痴。 And I'm sure I look like one too. 而且我敢肯定我也很像。

I tried all that stuff, trying to get the condition to work. 我尝试了所有这些东西,试图使条件起作用。 I just could not figure out why it wasn't working. 我只是不知道为什么它不起作用。

It just hit me. 它只是打我。 I was changing the code while I was debugging it, and it wasn't executing my changes. 我在调试代码时正在更改代码,但它没有执行我的更改。

I'm pretty embarrassed. 我很不好意思。 I was doing it right after all. 我毕竟是在做。 I was just... doing it wrong. 我只是...做错了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM