Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 764
merlin2011 Avatar asked Apr 10 '12 21:04

merlin2011


People also ask

How do I SELECT only part of a string in SQL?

The SUBSTRING() function extracts some characters from a string.

How do I SELECT a substring in SQL after a specific character?

To find the index of the specific character, you can use the CHARINDEX(character, column) function where character is the specific character at which you'd like to start the substring (here, @ ). The argument column is the column from which you'd like to retrieve the substring; it can also be a literal string.


1 Answers

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.

like image 103
Andrew Savinykh Avatar answered Sep 21 '22 06:09

Andrew Savinykh