Control structures syntax; IF THEN ELSE, CASE, WHILE .
IF THEN ELSE
The IF THEN ELSE syntax in TSQL is kinda weird if you ask me … I forget them ‘all the time’, created examples below for my reference.
IF THEN
if 1 = 1 begin print 'true' end go
IF THEN – short notation
if 1 = 1 print 'true' go
IF THEN ELSE
if 1 = 1 begin print 'true' end else begin print 'false' end go
IF THEN ELSE – short notation
if 1 = 1 print 'true' else print 'false' go
Multiple IF THEN ELSE blocks
if 1 = 1 begin print '1 = 1' end else if 1 = 2 begin print '1 = 2' end else if 1 = 3 begin print '1 = 3' end go
CASE
TSQL has the CASE control structure …
declare @i int, @r int set @i = 1 set @r = case @i when 1 then 1 when 2 then 2 else 0 end print @r go
WHILE
Eternal loop
while 1 = 1 print 'true' go
Simple WHILE loop
declare @i int set @i = 0 while @i < 10 begin print @i set @i = @i + 1 end go
Beautifully concise!
The best page on the internet for T-SQL control structures!
Thank you.