SQL Server 2012, has new features to perform Logical Functions such as CHOOSE and IIF that can be used to perform logical operations. In this tip we take a look at some basic examples of how this could be used.
In this tip we will discuss how to utilize the below mentioned newly introduced Logical Functions in SQL Server 2012.
1. CHOOSE Logical Function 2. IIF Logical Function
Using CHOOSE Logical Function
The CHOOSE function, which is available in SQL Server 2012, will return the item at the specified index from the list of values which are available. In this example we have 3 values and we are asking to select the third value in the list which is "SQL Server 2012".
SELECT 'New SQL Server Release' = CHOOSE(3, 'SQL Server 2008', 'SQL Server 2008 R2',
'SQL Server 2012')
Letís execute the below TSQL code which will use the CHOOSE function to return the month value using the CHOOSE logical function.
DISTINCT(FirstName + ' ' + LastName) AS Name
,DATEPART(DD, ModifiedDate) AS [Date]
,DATEPART(YYYY, ModifiedDate) AS [Year]
ORDER BY Name ASC
Using IIF Logical Function
The IIF function, which is available in SQL Server 2012, returns one of the two values depending upon whether the Boolean expression evaluates to either True or False.
DECLARE @FirstArgument INT = 10
DECLARE @SecondArgument INT = 20
SELECT IIF ( @FirstArgument > @SecondArgument , 'TRUE', 'FALSE' )
AS [Output Using IIF Logical Function]
Letís execute the below TSQL code which will use the IIF function to return the results. The logic is if the StateProvinceCode is between 0 and 95 then return France otherwise return Canada.
,IIF(TRY_PARSE(StateProvinceCode AS INT) Between 0 AND 95,'France','Canada') AS Country
WHERE StateProvinceCode IN ('95','AB')
Stay tuned for more tips on SQL Server 2012 and check out these related tips: