Logical Functions – IIF()

I am going continuing my short articles or tidbits on Transaction SQL logical functions.

These functions were introduced with the SQL Server 2012 release. Both functions have their origins from Visual Basic for Applications (VBA) framework.

I think of these function as decision trees. Especially when they are nested to several levels.

If you have a kid like I do, you might find the decision tree for dropped food funny. Please see image to left.

I will be exploring the IIF function today.

The example below uses the RAND function, to set two variables with random numbers between 1 and 10. The immediate if function takes an expression to evaluate and two values. It returns the first value if the expression is TRUE; otherwise, it returns the second value.

The output of each of the five batches is listed below.

Please note the number five after the key word GO. This tells the transaction processor to run the commands (batch) five times.

In a nutshell, this function can be replaced by the IF … ELSE control flow language. This syntax has been part of the T-SQL language for a long time.

Related posts

Leave a Comment