SQL Server CHOOSE() Function
The SQL Server (Transact-SQL) CHOOSE() function returns the Nth element of the list of items: val1 if N = 1, val2 if N = 2, and so on. It returns NULL if N is less than 1 or greater than the number of items specified as arguments.
Syntax
CHOOSE(N, val1, val2, val3,...)
Parameters
N |
Required. Specify the index number. |
val1, val2, val3,... |
Required. Specify the list of items. |
Return Value
Returns the Nth element of the list of items.
Example 1:
The example below shows the usage of CHOOSE() function.
SELECT CHOOSE(1, 'Learning', 'SQL Server', 'is', 'fun'); Result: 'Learning' SELECT CHOOSE(2, 'Learning', 'SQL Server', 'is', 'fun'); Result: 'SQL Server' SELECT CHOOSE(5, 'Learning', 'SQL Server', 'is', 'fun'); Result: NULL SELECT CHOOSE(0, 'Learning', 'SQL Server', 'is', 'fun'); Result: NULL SELECT CHOOSE(4, 'Learning', 'SQL Server', 'is', 'fun'); Result: 'fun' SELECT CHOOSE(3, 10, 20, 30, '40'); Result: 30
Example 2:
Consider a database table called EmployeeLogin with the following records:
EmpID | Name | Date | LoginTime |
---|---|---|---|
1 | John | 2019-10-25 | 09:20:38 |
2 | Marry | 2019-10-25 | 09:21:05 |
3 | Jo | 2019-10-25 | 09:24:35 |
4 | Kim | 2019-10-25 | 09:25:24 |
5 | Ramesh | 2019-10-25 | 09:27:16 |
The following query can be used to get the 2nd element from list of items specified by column records:
SELECT *, CHOOSE(2, Name, Date, LoginTime) AS CHOOSE_Value FROM EmployeeLogin;
This will produce a result similar to:
EmpID | Name | Date | LoginTime | CHOOSE_Value |
---|---|---|---|---|
1 | John | 2019-10-25 | 09:20:38 | 2019-10-25 |
2 | Marry | 2019-10-25 | 09:21:05 | 2019-10-25 |
3 | Jo | 2019-10-25 | 09:24:35 | 2019-10-25 |
4 | Kim | 2019-10-25 | 09:25:24 | 2019-10-25 |
5 | Ramesh | 2019-10-25 | 09:27:16 | 2019-10-25 |
6 | Suresh | 2019-10-25 | 09:28:19 | 2019-10-25 |
❮ SQL Server Functions