In this post explains how to use the IF...ELSE statement in SQL Server (Transact-SQL) with syntax and examples.
In SQL Server, the IF...ELSE statement is used to execute code when a condition is TRUE, or execute different code if the condition evaluates to FALSE.
The syntax for the IF...ELSE statement in SQL Server (Transact-SQL) is:
Optional. You would use the ELSE condition when you want to execute a set of statements when the IF condition evaluated to FALSE (ie: the condition was not met).
Let's look at an example of how to use the IF...ELSE statement in SQL Server (Transact-SQL).
For example:
In this IF...ELSE statement example, we will print AODBA.com' if the variable @site_value is less than 25. Otherwise, we will print 'mySite.com'.
Since the ELSE condition is optional, you are not required to include the ELSE condition in the IF...ELSE statement in SQL Server.
Let's look at an example of how to exclude the ELSE condition from the IF...ELSE statement in SQL Server (Transact-SQL).
For example:
In this IF...ELSE statement example, we will print 'AODBA.com' if the variable @site_value is less than 25. There is no ELSE condition in this IF...ELSE statement example.
Since we can't write an ELSE IF condition within the IF...ELSE statement, we need to nest multiple IF...ELSE statements instead.
Let's look at an example of how to nest multiple IF...ELSE statements in SQL Server (Transact-SQL).
For example:
In this nested IF...ELSE statement example, we will print 'AODBA.com' if the variable @site_value is less than 25.
Otherwise, the first ELSE condition will be executed. Within this ELSE condition, there is a nested IF...ELSE statement that will print 'mySite.com' if the variable @site_value is less than 50. Finally, if no other condition is met, 'data.com' will print.