Search This Blog

Wednesday, July 25, 2012

While SQL Server

SQL ServerControl of Flow > While

While represents repeated execution of an SQL statement or statement block.
  • as long as the specified condition is true the statements are executed repeatedly 
  • the execution of statements in the WHILE loop can be controlled from inside the loop with the BREAK and CONTINUE keywords

Syntax:

WHILE Boolean_expression { statement_block | BREAK | CONTINUE }


Example

declare @t nvarchar(max)
declare @t1 nvarchar(max)
declare @p int


set @t = 'fld1:"val1";fld2:"val2","val3";fld3:"val4";'
set @p = CHARINDEX(';', @t);

while @p > 0
begin
     set @t1 = SUBSTRING (@t, 0, @p)
     set @t = SUBSTRING (@t, @p+1, len(@t) - @p)
     set @p = CHARINDEX(';', @t);
        select @t1
     if @p = 0
      break
    else
      continue
end

Result: