In SQL Server, you can use the CASE statement to perform conditional logic within a SELECT statement. The CASE statement allows you to define multiple conditions and their corresponding actions.
Here's the basic syntax for using the CASE statement in a SELECT statement:
sqlSELECT column1, column2,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END AS column_alias
FROM your_table
Let's break down the syntax:
column1
,column2
, etc.: These are the columns you want to retrieve in your SELECT statement.CASE
: Begins the CASE statement.WHEN condition1 THEN result1
: Specifies the first condition and its corresponding result. If the condition evaluates to true, the result1 value will be returned.WHEN condition2 THEN result2
: Specifies the second condition and its corresponding result. If the condition evaluates to true, the result2 value will be returned.ELSE result3
: Specifies the default result if none of the conditions evaluate to true.END
: Ends the CASE statement.AS column_alias
: Assigns an alias to the column generated by the CASE statement.
Here's an example that demonstrates the usage of the CASE statement in a SELECT statement:
sqlSELECT OrderID, OrderDate,
CASE
WHEN TotalAmount > 1000 THEN 'High'
WHEN TotalAmount > 500 THEN 'Medium'
ELSE 'Low'
END AS OrderPriority
FROM Orders
In this example, the SELECT statement retrieves the OrderID
and OrderDate
columns from the Orders
table. The CASE statement checks the value of the TotalAmount
column for each row and assigns the appropriate priority ('High', 'Medium', or 'Low') based on the conditions specified.
Remember to replace your_table
with the actual name of your table and adjust the conditions and results in the CASE statement according to your requirements.
Comments
Post a Comment