Flow Control
Learn to use flow control with conditional logic in T-SQL queries.
We'll cover the following
T-SQL can be considered a programming language because we can add conditional logic to our T-SQL queries. In other words, T-SQL supports the IF
…ELSE
construct, like the majority of procedural programming languages.
Syntax
The IF
…ELSE
construct has this syntax in T-SQL:
IF [Condition]
BEGIN
[Actions to perform if the condition is true]
END
ELSE
BEGIN
[Actions to perform if the condition is false]
END
The [Condition]
in the snippet above is any expression that returns a boolean value (true or false). If we do not need to handle situations when the [Condition]
is false, then we can safely omit the ELSE
block:
IF [Condition]
BEGIN
[Actions to perform if the condition is true]
END
Example
We have the @Age
variable of type INT
, which stores the user’s age. If it is below 21
, we’ll print 'Not allowed'
. Otherwise, we’ll output 'Access granted'
:
Get hands-on with 1400+ tech skills courses.