I wrote a T-SQL Statement similar like this (the original one looks different but I want to give an easy example here):
SELECT first_name +
CASE last_name WHEN null THEN 'Max' ELSE 'Peter' END AS Name
FROM dbo.person
This Statement does not have any syntax errors but the case-clause always chooses the ELSE-part - also if the last_name is null. But Why?
What I want to do is to unite first_name and last_name, but if last_name is null the whole name becomes null:
SELECT first_name +
CASE last_name WHEN null THEN '' ELSE ' ' + last_name END AS Name
FROM dbo.person
Do you know where the problem is?
Use the CONCAT function available in SQL Server 2012 onward.
I tried casting to a string and testing for a zero-length string and it worked.
You can use IsNull function
if one column is null you would get an empty char
Compatible with Microsoft SQL Server 2008+
The WHEN part is compared with ==, but you can't really compare with NULL. Try
instead or COALESCE:
(' '+last_name is NULL when last_name is NULL, so it should return '' in that case)
The issue is that NULL is not considered to be equal to anything even not to itself, but the strange part is that is also not not equal to itself.
Consider the following statements (which is BTW illegal in SQL Server T-SQL but is valid in My-SQL, however this is what ANSI defines for null, and can be verified even in SQL Server by using case statements etc.)
SELECT NULL = NULL -- Results in NULL
SELECT NULL <> NULL -- Results in NULL
So there is no true/false answer to the question, instead the answer is also null.
This has many implications, for example in
WHEN NULL
condition )SELECT a + NULL -- Results in NULL
One can override this behavior in SQL Server by specifying
SET ANSI_NULLS OFF
, however this is NOT recommended and should not be done as it can cause many issues, simply because deviation of the standard.(As a side note, in My-SQL there is an option to use a special operator
<=>
for null comparison.)In comparison, in general programming languages null is treated is a regular value and is equal to itself, however the is the NAN value which is also not equal to itself, but at least it returns 'false' when comparing it to itself, (and when checking for not equals different programming languages have different implementations).
Note however that in the Basic languages (i.e. VB etc.) there is no 'null' keyword and instead one uses the 'Nothing' keyword, which cannot be used in direct comparison and instead one needs to use 'IS' as in SQL, however it is in fact equal to itself (when using indirect comparisons).
try:
This adds the space to the last name, if it is null, the entire space+last name goes to NULL and you only get a first name, otherwise you get a firts+space+last name.
this will work as long as the default setting for concatenation with null strings is set:
this shouldn't be a concern since the
OFF
mode is going away in future versions of SQl Server