Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CASE statement with isnull and else

Tags:

sql

tsql

case

I have a column Color which contains Black, Red, NULL, WW, RR.

I want a column which has

if color black then 'B'
if color red then 'r'
if color is Null then 'Empty'
for all other entries 'n/a'

I'm using the following, but it throws an error:

SELECT Name,
        CASE color
            WHEN 'black' THEN 'b'
            WHEN 'red' THEN 'r'
            WHEN ISNULL(color, 'empty')
            else 'n/a'
           END AS Color_code
FROM SalesLT.Product;
like image 920
Myurathan Kajendran Avatar asked Jan 27 '17 20:01

Myurathan Kajendran


2 Answers

You can use either CASE structure to do this, but you can't call a function if you use the CASE fieldname WHEN approach, so you can either use CASE WHEN fieldname condition:

SELECT Name,
        CASE WHEN color = 'black' THEN 'b'
            WHEN color = 'red' THEN 'r'
            WHEN color IS NULL THEN  'empty'
            else 'n/a'
           END AS Color_code
FROM SalesLT.Product;

OR:

SELECT Name,
        CASE color
            WHEN 'black' THEN 'b'
            WHEN 'red' THEN 'r'
            WHEN NULL THEN 'empty'
            else 'n/a'
           END AS Color_code
FROM SalesLT.Product;
like image 187
Hart CO Avatar answered Nov 05 '22 08:11

Hart CO


You could try this way

  SELECT Name,
          CASE 
              WHEN color = 'black' THEN 'b'
              WHEN color = 'red' THEN 'r'
              WHEN color is null  THEN  'empty'
                ELSE 'n/a'
          END AS Color_code
  FROM SalesLT.Product;
like image 36
ScaisEdge Avatar answered Nov 05 '22 09:11

ScaisEdge