sqlsql-serversql-server-2008t-sql

How do I perform a simple string mapping as part of a t-sql select?


In T-SQL, I can do arithmetic as part of a select. For example, suppose I have a table Math with a column named Decimal. I can do the following query.

SELECT 100*Decimal FROM Math

I wonder if it's also possible to do logic in the SELECT where I create a mapping such as { A=>B, F=>Z} so that every time the column is A, it returns B, and every time the column is F, it returns Z.

I apologize if this is a newb question, because I'm not very experienced in SQL.


Solution

  • I think you want to use the CASE expression:

    SELECT 
      CASE column1 
        when 'A' THEN 'B' 
        when 'F' THEN 'Z' 
      END 
    FROM Tbl
    

    Also note that there are two different syntaxes for it, choose one that is most appropriate for you.