SQL 如何在 tsql 中实现 do-while 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1512726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:51:34  来源:igfitidea点击:

How to implement a do-while loop in tsql

sqlsql-servertsqlwhile-loopcontrol-flow

提问by Rodrigo

I'm trying to figure how to implement this in TSQL

我想弄清楚如何在 TSQL 中实现这一点

do 
  update stuff set col = 'blah' where that_row = 'the right one'
  select trash from stuff ...
until some_condition

The only iterative control flow sentence provided by Transact-SQL is while (condition) sentencesthat first evaluates the condition and if that condition is true then execute the sentence.

Transact-SQL 提供的唯一迭代控制流语句是while (condition) sentences首先评估条件,如果条件为真,则执行该语句。

I'm thinking in a scenario like execute a UPDATE statement over a table until some condition triggered y the last UPDATE executed is achieved.

我在想一个场景,比如在表上执行 UPDATE 语句,直到某些条件触发 y 最后执行的 UPDATE 实现。

Most important, I'm looking for the less-dirty approach to this problem (Duplicating the UPDATE before the WHILE does not make too much sense to me as the UPDATE sentence can be arbitrarily long and complex)

最重要的是,我正在寻找解决这个问题的不太脏的方法(在 WHILE 之前复制 UPDATE 对我来说没有太大意义,因为 UPDATE 语句可以任意长和复杂)



EDIT: The problem I'm trying to solve involve multiple UPDATE statements under the same table, each one taking and transforming the values from the previous iterations. This is not possible to do in just one big UPDATE statement, as each row will be evaluated and updated only once, so a loop is the only way I can figure out to make this mess to work.

编辑:我试图解决的问题涉及同一个表下的多个 UPDATE 语句,每个语句都从以前的迭代中获取并转换值。这在一个大的 UPDATE 语句中是不可能的,因为每一行只会被评估和更新一次,所以循环是我能想出的唯一方法来让这个混乱工作。

回答by Mitch Wheat

This is effectively a Do-While loop:

这实际上是一个 Do-While 循环:

WHILE (1=1)
  BEGIN

  -- Do stuff...

  IF (some_condition is true)
     BREAK;

  END

But as @Joel Coehoorn noted, always try to use a set based approach first. I would only resort to a loop if I can't think of a way to solve using set operations.

但正如@Joel Coehoorn 指出的那样,始终首先尝试使用基于集合的方法。如果我想不出使用集合操作解决的方法,我只会求助于循环。