sql - Break keyword vs Variable in WHILE loop -


we using while loop in sql server 2008 instead of cursor. want find method best write while loop in procedure.

method 1 (using break keyword):

declare @v_counter int = 1;  while (1 = 1) begin     print @v_counter;     set @v_counter = @v_counter + 1;      if @v_counter = 4     begin         break;     end end 

method 2 (using bool variable):

declare @v_counter int = 1, @v_closeloop tinyint = 1;  while (@v_closeloop = 1) begin     print @v_counter;     set @v_counter = @v_counter + 1;      if @v_counter = 4     begin        set @v_closeloop = 0;     end end  

my questions are:

  • which method have use or both same?
  • is there other method can use?

thanks in advance...

which method have use or both same? no, both not same.

setting variable 0 still execute lines after that, nothing else in loop executed after break.

declare @v_counter int = 1;  while (1 = 1) begin     print @v_counter;     set @v_counter = @v_counter + 1;      if @v_counter = 4     begin        break;     end     print 'stackoverflow' // not executed. end      declare @v_counter int = 1, @v_closeloop tinyint = 1;  while (@v_closeloop = 1) begin     print @v_counter;     set @v_counter = @v_counter + 1;      if @v_counter = 4     begin        set @v_closeloop = 0;     end     print 'stackoverflow' // executed. end  

using break clean approach, setting variable zero, code easy maintain when use break other way around.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -