Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server String Concatenation with Null

I am creating a computed column across fields of which some are potentially null.

The problem is that if any of those fields is null, the entire computed column will be null. I understand from the Microsoft documentation that this is expected and can be turned off via the setting SET CONCAT_NULL_YIELDS_NULL. However, there I don't want to change this default behavior because I don't know its implications on other parts of SQL Server.

Is there a way for me to just check if a column is null and only append its contents within the computed column formula if its not null?

like image 733
Alex Avatar asked May 26 '10 21:05

Alex


People also ask

Can we concatenate string and NULL in SQL?

When SET CONCAT_NULL_YIELDS_NULL is ON, concatenating a null value with a string yields a NULL result. For example, SELECT 'abc' + NULL yields NULL . When SET CONCAT_NULL_YIELDS_NULL is OFF, concatenating a null value with a string yields the string itself (the null value is treated as an empty string).

How do I concatenate NULL values in a string in SQL Server?

One way to concatenate multiple strings or columns is to use the "+" operator. For the rows where MiddleName is NULL, the concatenation result will be NULL.

Can you concatenate a string with NULL?

Using the String.concat() method is a good choice when we want to concatenate String objects. The empty String returned by the getNonNullString() method gets concatenated to the result, thus ignoring the null objects.

Can we concatenate NULL values?

Concatenating Data When There Are NULL ValuesTo resolve the NULL values in string concatenation, we can use the ISNULL() function. In the below query, the ISNULL() function checks an individual column and if it is NULL, it replaces it with a space.


1 Answers

You can use ISNULL(....)

SET @Concatenated = ISNULL(@Column1, '') + ISNULL(@Column2, '') 

If the value of the column/expression is indeed NULL, then the second value specified (here: empty string) will be used instead.

like image 152
marc_s Avatar answered Oct 13 '22 17:10

marc_s