33

I'm trying to figure how to implement this in 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) sentences that first evaluates the condition and if that condition is true then execute the sentence.

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.

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)


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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Rodrigo
  • 4,365
  • 3
  • 31
  • 49
  • 4
    If you're thinking flow-control for database code, you're doing it wrong. – Joel Coehoorn Oct 03 '09 at 03:45
  • 4
    Don't be so inflexible, sometimes business logic needs to be developed in stored procedures. – Rodrigo Oct 03 '09 at 03:53
  • @rodrigo, he isn;talking about it being a stored proc, he is talking about using set theory and not a looop at all. It is possible to avoid the loop about 99% of teh time and it is ALWAYS preferable to do so if you can. – HLGEM Jan 30 '15 at 21:42
  • @HLGEM did you read the EDIT section of my question? you're right, 99% of the time a properly build query solves everything, i was asking because some times you have to deal with a case in that 1%... – Rodrigo Feb 12 '15 at 17:19

1 Answers1

48

This is effectively a Do-While loop:

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.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 1
    1 is not a boolean value, instead of this (1=1) can do the job. This solution works and is very simple. Seems obvious after reading! Thanks a lot. – Rodrigo Oct 03 '09 at 04:01
  • 1
    Just wanted to add that the () for while isn't required unless it was a select of some kind. – Cody Konior Feb 01 '17 at 13:16