Monday, February 4, 2008

Using CASE in SQL Queries

This morning, I've got to know the CASE functionality of SQL Server (which surely exists in other databases, too). With CASE you can set values for a column under specified conditions, e.g.

SELECT
Column1,
Column2 = CASE
WHEN Column1 = '1' THEN 'Y'
ELSE 'N'
END
FROM Table1

Thus, column2 will be set with 'Y' if column1 has the value '1'; otherweise 'N' will be set.

PS: An overview by Craig S Mullins helps to understand this method in more detail.

No comments: