Reputation: 2378
I have a large case expression
e.g.
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END +
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END as [Test]
Now the [Test] column returns some NULLS. How can i wrap this CASE expression with (ISNULL, '') so that if it is NULL it is just blank?
What is the cleanest way to accomplish this with a very large case statement?
Upvotes: 1
Views: 6357
Reputation: 140
I think the best way is to use a function for large case statement, this will be more readable for you. And easier to implement your solutions.
Upvotes: 0
Reputation: 63338
I may be missing the point but is there something you don't like about
ISNULL(
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END +
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END
, '')
AS [Test]
?
Upvotes: 3
Reputation: 50163
I would do :
SELECT ISNULL([Test], '')
FROM table t CROSS APPLY
( VALUES (CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END +
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END)
) tt ([Test]);
However, you can also apply ISNULL()
to entire huge case expression :
SELECT ISNULL((CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END +
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END), ''
)
. . .
The only advantage of APPLY
is that you can use [Test]
column anywhere or more than one time.
Upvotes: 1
Reputation: 95561
Just wrap the entire expression with an ISNULL
:
ISNULL(
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END +
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END,'') as [Test]
Alternatively, you could use CONCAT
, however, this would change the logic of your query slightly. If one expression didn't return a NULL
and the other did, you would now get a value. NULL + {Non NULL Expression}
= NULL
however, CONCAT(NULL,{Non NULL Expression})
= {Non NULL Expression}
.:
CONCAT(
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END,
CASE WHEN ... THEN ... ELSE
CASE WHEN ... THEN ... ELSE '' END ELSE '' END) as [Test]
CONCAT
will never return NULL
. If every expression has the value NULL
, an empty string ((n)varchar
) is returned.
Upvotes: 1