27

First of all I would like to know how does CAST work with NULL fields and how does it behave when the value is NULL?

For example in the expression:

(CAST(INT_FIELD as nvarchar(100))

what happens if the value INT_FIELD is NULL?

The reason is that when I'm trying to do the following:

SELECT (CAST(INT_FIELD as nvarchar(100)) + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;

I'm getting NULL even though the SOME_OTHER_FIELD is not null. I'm guessing it has some kind of logic that NULL + something = NULL but I'm not sure.

How can I control this behavior?

4
  • 2
    Why are you casting an integer field to nvarchar(100)? Max length is 11. Sep 26, 2011 at 15:44
  • 1
    @Martin Smith - I just used it as a dummy value, thanks for the tip though, I didn't know that max length is 11. What is the max length for a decimal?
    – TehBoyan
    Sep 26, 2011 at 15:46
  • 2
    depends on precision and scale. But 40 I would have though for max precision 38 with a decimal point and a minus symbol. Sep 26, 2011 at 15:49
  • 1
    Read up on CONCAT_NULL_YIELDS_NULL.
    – Ian Kemp
    May 11, 2018 at 8:12

4 Answers 4

40

You need to use ISNULL or COALESCE, since most row operation between a NULL is gonna result in NULL. CAST of a NULL returns NULL and NULL + something is also NULL. In your example you should do something like this:

SELECT ISNULL(CAST(INT_FIELD as nvarchar(100)),'') + ' ' + ISNULL(SOME_OTHER_FIELD,'')
FROM SOME_TABLE;

Of course, in my example, if both fields are NULL it will return ' ' instead of '', but you get the idea.

1
4

Look into COALESCE, where you can find the first non-null and return 0 if all are null, e.g:

SELECT (CAST(COALESCE(INT_FIELD,0) as nvarchar(100)) + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;
4

Try using COALESCE

SELECT COALESCE(CAST(INT_FIELD as nvarchar(100), '') + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;
2
3

Normally, NULL +(-,/,*, etc) something = NULL. You can use

SELECT ISNULL(CAST(INT_FIELD as nvarchar(100)),'') 
+ ' ' + ISNULL(SOME_OTHER_FIELD FROM SOME_TABLE,'')

or you can SET CONCAT_NULL_YIELDS_NULL OFF (more details)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.