Alternatives · Basic Logics

Common Alternatives to IF ELSE Logic in SQL Server with Simple Example

Below are the Common Alternatives of IF ELSE Logic in SQL Server that was given with simple example.

IF ELSE LOGIC

SYNTAX
IF Boolean_expression   
     { sql_statement | statement_block }   
[ ELSE   
     { sql_statement | statement_block } ]
--ELSE Block is OPTIONAL
SQL QUERY WITH SIMPLE EXAMPLE
--IF ELSE LOGIC
IF 1>0
	SELECT 'True' AS RESULT;
ELSE
	SELECT 'False' AS RESULT;

CASE EXPRESSION

The main use of CASE Expression returns a value based on one or more conditions.
We can use CASE Expression anywhere in a SQL statement where an expression is allowed.
It makes data comparable, performs checks to protect against errors like Divide by zero.

SYNTAX
CASE  
     WHEN when_expression THEN result_expression [ ...n ]   
     [ ELSE else_result_expression ]   
END 
--ELSE Block is OPTIONAL
SQL QUERY WITH SIMPLE EXAMPLE
--CASE EXPRESSION
SELECT 
	CASE 
		WHEN 1>0 
			THEN 'True' 
		ELSE 'False' 
	END AS RESULT;

IIF FUNCTION

Returns one of two values, depending on whether the Boolean expression evaluates to true or false.

SYNTAX
IIF ( boolean_expression, true_value, false_value )
--false value acts as ELSE Case here. 
SQL QUERY WITH SIMPLE EXAMPLE
--IIF FUNCTION
SELECT IIF( 1>0 ,'True' ,'False' ) AS RESULT;

CONCLUSION

In this blog post, we covered the using of IF ELSE, CASE Expressions and IIF Function in SQL Server.

Thanks for reading!

Advertisement

3 thoughts on “Common Alternatives to IF ELSE Logic in SQL Server with Simple Example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s