Home > Enterprise >  Is there a way to simplify this TSQL Case statement?
Is there a way to simplify this TSQL Case statement?

Time:06-18

Is there a simpler way to write the case statement in the select or is this the only way? Basically if COL B AND COL C are not NULL, THEN col b - col c, if one is null, select the other.

SELECT
    COL_A AS [A],
    CASE WHEN NULLIF(COL_B, '') IS NOT NULL AND NULLIF(COL_C, '') IS NOT NULL
             THEN CONCAT(COL_B, ' - ', COL_C)
         WHEN NULLIF(COL_B, '') IS NULL AND NULLIF(COL_C, '') IS NOT NULL
             THEN COL_C
         WHEN NULLIF(COL_B, '') IS NOT NULL AND NULLIF(COL_C, '') IS NULL
             THEN COL_B
     END AS [B]

CodePudding user response:

Basically if COL B AND COL C are not NULL, THEN col b - col c, if one is null, select the other.

Using CONCAT_WS:

SELECT CONCAT_WS(' - ', COL_B, COL_C) AS [B]

db<>fiddle demo

  • Related