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?
The database development standards in our organization state the varchar fields should not allow null values. They should have a default value of an empty string ("").
How do I cast a NULL to a string in SQL? There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, ”) will return empty String if the column value is NULL.
SQL Server's CAST() and CONVERT() methods can be used to convert VARCHAR to INT.
We can replace NULL values with a specific value using the SQL Server ISNULL Function. The syntax for the SQL ISNULL function is as follow. The SQL Server ISNULL function returns the replacement value if the first parameter expression evaluates to NULL.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With