kzhang12
kzhang12

Reputation: 211

How to set multiple columns to null if they have meet some condition?

I have a table which has 8 columns, Child0, Child1, Child2, Child3, Child4, Child5, Child6, Childx.

If Child0=Childx, then Child0=null else Child0 remains the same. The same logic applies to Child1 - Child 6.

I can only think of:

SELECT 
CASE 
    WHEN Child6=Childx then null 
    ELSE Child6
END AS CHILD6,
CASE 
    WHEN Child5=Childx then null 
    ELSE Child5
END AS CHILD5,
...
FROM TABLE

Is there some simple way to do that?

Upvotes: 2

Views: 2921

Answers (1)

Lamak
Lamak

Reputation: 70678

You can use NULLIF:

SELECT NULLIF(Child0,Childx) Child0,
       NULLIF(Child6,Childx) Child6,
       ....
FROM dbo.YourTable

Upvotes: 8

Related Questions