SQL Case Statement
Here's a simple example of a SQL CASE statement for Microsoft SQL Server:
SELECT Day = CASE WHEN (DateAdded IS NULL) THEN 'Unknown' WHEN (DateDiff(day, DateAdded, getdate()) = 0) THEN 'Today' WHEN (DateDiff(day, DateAdded, getdate()) = 1) THEN 'Yesterday' WHEN (DateDiff(day, DateAdded, getdate()) = -1) THEN 'Tomorrow' ELSE DATENAME(dw , DateAdded) END FROM Table
In this CASE statement example we are switching on a column called
DateAdded which is a date time field. Using various date functions we are creating a column called
Day with values Today, Yesterday, Tomorrow, or the day of the week (eg Sunday).
You can also add a
WHERE clause, and select other columns from the query
If you found this handy you might also like my SQL Server Cheat Sheet, enjoy.
Like this? Follow me ↯Tweet Follow @pfreitag
SQL Case Statement was first published on October 15, 2008.
If you like reading about sql, case, statement, or sqlserver then you might also like:
- Getting ColdFusion SQL Statements from SQL Server Trace
- Try Catch for SQLServer T-SQL
- INFORMATION_SCHEMA Support in MySQL, PostgreSQL
- Backwards LIKE Statements
- SQL to Select a random row from a database table
- Temporary Stored Procedures on SQL Server
- SQL Reserved Key Words Checker Tool
- Top 3 differences between PostgreSQL and MS SQL