Sql – in sqlserver, need to select one of two columns, can a case statment do this

casesql serversql-server-2008

My table:

Users (userID, col1, col2)

I want to make a generic stored procedure, but I need to return EITHER col1 or col2 in a query.

Can I case statement handle this situation?

SELECT userID, col1
FROM Users

OR

SELECT userID, col2
FROM Users

Best Answer

Using CASE:

SELECT t.userid,
       CASE
         WHEN [something to evaluate why to show col1 vs col2 ] THEN
           t.col1
         ELSE
           t.col2
       END
  FROM USERS t

Using COALESCE:

SELECT t.userid,
       COALESCE(t.col1, t.col2)
  FROM USERS t

COALESCE returns the first column value that isn't null, starting from the left.