Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control casting of null int field to varchar in sql server?

Tags:

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?

like image 681
TheBoyan Avatar asked Sep 26 '11 15:09

TheBoyan


People also ask

Can varchar take NULL?

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 value in SQL?

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.

Can a varchar be cast to an int?

SQL Server's CAST() and CONVERT() methods can be used to convert VARCHAR to INT.

How do you replace a NULL value in a string in SQL?

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.


2 Answers

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.

like image 164
Lamak Avatar answered Oct 16 '22 08:10

Lamak


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; 
like image 22
downforce Avatar answered Oct 16 '22 06:10

downforce