How do you use the CHOOSE function to return a value from a list of values based on a specified index in SQL Server?
Posted by SamPetr
Last Updated: June 27, 2024
In SQL Server, the CHOOSE function can be used to return a value from a list of values based on a specified index. The CHOOSE function takes an integer index as its first argument and a list of values (which can be of different data types) as the subsequent arguments. The syntax for the CHOOSE function is:
CHOOSE(index, value1, value2, value3, ...)
- index: An integer that specifies which value to return from the list. It must be between 1 and the number of values provided. - value1, value2, value3, ...: The list of values from which to choose.
Example
Let's say we have a table called Products with a column CategoryID, and we want to return the name of a category based on the CategoryID. We can use the CHOOSE function to achieve this.
SELECT 
    ProductID,
    ProductName,
    CategoryID,
    CHOOSE(CategoryID, 'Electronics', 'Clothing', 'Groceries', 'Home Appliances') AS CategoryName
FROM 
    Products;
In this example: - If CategoryID is 1, the CategoryName will be Electronics. - If CategoryID is 2, the CategoryName will be Clothing. - If CategoryID is 3, the CategoryName will be Groceries. - If CategoryID is 4, the CategoryName will be Home Appliances.
Important Note
The CHOOSE function will return NULL if the index is less than 1 or greater than the number of values specified. Therefore, you should ensure that the index value is within the valid range to avoid unexpected results.
Example with Error Handling
You can also combine CHOOSE with a CASE statement or another conditional logic to handle cases where the index might be out of bounds:
SELECT 
    ProductID,
    ProductName,
    CategoryID,
    CASE 
        WHEN CategoryID BETWEEN 1 AND 4 THEN CHOOSE(CategoryID, 'Electronics', 'Clothing', 'Groceries', 'Home Appliances')
        ELSE 'Unknown Category'
    END AS CategoryName
FROM 
    Products;
This code ensures that if CategoryID is not within the range of 1 to 4, it returns 'Unknown Category'.