Tuesday, March 31, 2009

T-SQL SELECT Using CASE and String Concatenation

Here I'm selecting the ID field followed by a concatenation of 3 different subject fields, depending on whether or not the fields are NULL.

SELECT
ID,
CASE
WHEN Subject2 IS NULL THEN
Subject1
WHEN Subject2 IS NOT NULL AND Subject3 IS NULL THEN
Subject1 + ' : ' + Subject2
ELSE Subject1 + ' : ' + Subject2 + ' : ' + Subject3
END AS TheSubject
FROM Subjects
ORDER BY TheSubject

No comments: