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.
- Getting ColdFusion SQL Statements from SQL Server Trace - June 16, 2008
- Try Catch for SQLServer T-SQL - April 7, 2008
- INFORMATION_SCHEMA Support in MySQL, PostgreSQL - February 18, 2008
- Backwards LIKE Statements - January 10, 2007
- SQL to Select a random row from a database table - September 14, 2005
- Docker Container exited with code 137
- Why is my cron.daily script not running?
- Announcing FuseGuard Version 3
- CFSummit 2017
- Java Unlimited Strength Crypto Policy for Java 9 or 1.8.0_151
- Java 9 Security Enhancements
- Upcoming CFML Conferences in April 2017
- CFSummit 2016 Slides