Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional value replacement in SQL Server

I have a table that has several columns. The value of one column is 0 or 1. I want to write a query that returns "Hello" if the value was 0, or "Bye" if it was 1. What is the appropriate way to write this query?

like image 896
Tavousi Avatar asked Dec 11 '11 14:12

Tavousi


People also ask

How do you replace and condition in SQL?

SQL Server REPLACE() FunctionThe REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive. Tip: Also look at the STUFF() function.

How do I remove a specific character from a string in SQL?

The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.

Can we use Replace with UPDATE in SQL?

This blog covers using the REPLACE function to selectively replace text inside a string in SQL Server. The REPLACE function is easy to use and also very handy with an UPDATE statement.


2 Answers

Use a CASE expression

SELECT CASE YourCol
         WHEN 0 THEN 'Hello'
         WHEN 1 THEN 'Bye'
       END AS SomeAlias
FROM   YourTable  
like image 122
Martin Smith Avatar answered Sep 23 '22 11:09

Martin Smith


If you choose multi/all columns, please try with below:

SELECT Column1, Column2,  -- Put other column name here 
        CASE TargetColumnName
         WHEN 0 THEN 'Hello'
         WHEN 1 THEN 'Bye'
       END AS TargetAliasColumnName
FROM   YourTableName 
like image 21
Elias Hossain Avatar answered Sep 19 '22 11:09

Elias Hossain