Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to simplify this TSQL Case statement?

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]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading