Microsoft SQL Server 2012 Bible
by Adam Jorgensen, Jorge Segarra, Patrick LeBlanc, Jose Chinchilla, Aaron Nelson
Procedural Flow
At first glance, it appears that T-SQL is weak in procedural-flow options. Although it's less rich than some other languages, it suffices. The data-handling boolean extensions — such as EXISTS, IN, and CASE — offset the limitations of IF and WHILE.
Using If for Conditional T-SQL
This is your grandfather's IF. The T-SQL IF command determines the execution of only the next single statement — one IF, one command. In addition, there's no THEN and no END IF command to terminate the IF block:
IF Condition Statement;
In the following script, the IF condition should return a false, preventing the next command from executing:
IF 1 = 0 PRINT ‘Line One'; PRINT ‘Line Two';
Result:
Line Two
Using Begin/End to Conditionally Execute Multiple Statements
An IF command that can control only a single command is less than useful. However, a BEGIN/END block can make multiple commands appear to the IF command as the next single command:
IF Condition Begin; Multiple lines; End;
Using If exists() as an Existence-Based Condition
While the IF command may seem limited, the condition clause can include several powerful SQL features similar to a WHERE clause, such as IF EXISTS() and IF. . .IN().
The IF EXISTS() structure uses the presence of any rows returned from a ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access