SQL Server 2012 CHOOSE Function

Microsoft-SQL-Server-2012

In SQL Server 2012 there is a new function called CHOOSE that takes in an offset, and a list of options.  Choose is a function that returns the item at a specific index.

Syntax:
—CHOOSE (index, val_1, val_2, val_3, …)
—If the index is greater than the number of values or less than 1 it returns NULL
—This is easier than using a CASE statement in most examples.
Example:
-- CHOOSE
-- returns the item at a specific index
DECLARE @corners as int= 6
SELECT CHOOSE (@corners, 'point', 'line', 'triangle', 'square','pentagon','hexagon', 'heptagon', 'octagon')

-- the old way using case.
SELECT @corners
   WHEN 1 THEN 'point' 
   WHEN 2 THEN 'line'
   WHEN 3 THEN 'triangle' 
   WHEN 4 THEN 'square'
   WHEN 5 THEN 'pentagon' 
   WHEN 6 THEN 'hexagon'
   WHEN 7 THEN 'heptagon'
   WHEN 8 THEN 'octagon' 
   ELSE NULL 
END

You can read more here.

Advertisements

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 )

Google+ photo

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

Connecting to %s