Monday, August 5, 2013

Choose in SQL Server 2012

Overview

SQL Server 2012 has introduced 2 new logical functions. IIF & Choose.
Let's go over CHOOSE function. It returns a value at specific index from a list. 

Scenarios & Example


  •  Basic Use


SELECT CHOOSE(3, 'SQL 2005', 'SQL 2008', 'SQL 2012')



(No column name)
SQL 2012

So we can see that, it gives 3rd value from the set of value we have provided. 
Let's test if we give some unusual index values

SELECT 'CASE 1.1' [Case], CHOOSE(1.1, 'SQL 2005', 'SQL 2008', 'SQL 2012')  [Value]
UNION ALL
SELECT 'CASE 1.9' , CHOOSE(1.9, 'SQL 2005', 'SQL 2008', 'SQL 2012')
UNION ALL
SELECT 'CASE -3' , CHOOSE(-3, 'SQL 2005', 'SQL 2008', 'SQL 2012')
UNION ALL

SELECT 'CASE 5' , CHOOSE(5, 'SQL 2005', 'SQL 2008', 'SQL 2012')

Case
Value
CASE 1.1
SQL 2005
CASE 1.9
SQL 2005
CASE -3
NULL
CASE 5
NULL

  •  Advance Use

Let's say, we have a date stored in a table, we want to know whether it is weekday/weekend, then this is how we can write using CHOOSE.

SELECT EmployeeName,EmployeeDOB, DATENAME(DW,EmployeeDOB), DATEPART(DW,EmployeeDOB),

CHOOSE(DATEPART(DW,EmployeeDOB), 'WEEKEND', 'Weekday', 'Weekday', 'Weekday', 'Weekday', 'Weekday', 'WEEKEND') FROM Employee

EmployeeName
EmployeeDOB
(No column name)
(No column name)
(No column name)
John
4/4/1989
Tuesday
3
Weekday
Rob
5/28/1990
Monday
2
Weekday
Bob
3/16/1991
Saturday
7
WEEKEND
Ryan
12/5/1983
Monday
2
Weekday
Lisa
9/14/1979
Friday
6
Weekday

We can also write the same thing using CASE statement but the only thing CHOOSE will be easier to write than CASE.
w.r.t Performance, there is no difference either you use CASE or CHOOSE, both are same. CHOOSE internally uses CASE only.

No comments:

Post a Comment