Concatenating Strings to NULL values

We recently ran into this situation of reports containing nothing but blank spaces. When investigated the reason was that the String concatenation statement was written as a general statement. There is nothing wrong in the statement, it works fine when the variables have a value but does not work when one of the variables is NULL.

The “SELECT @FinalString” statement returns NULL since the variable @String1 is NULL. When such a variable is concatenated with other set of variables or string values it would all result in NULL and the string message(s) that is to be used will not return the desired output (resulting in blank spaces in reports in one of our case).

In order to overcome such issues, the ISNULL function can be used which checks the value and replaces with the value to be replaced if NULL is found. The same statement is rewritten and ISNULL is implemented to check for NULL values in @String1 variable, if @String1 is NULL, then ‘EMPTY STRING1’ is included in the final string and results in a meaningful string value instead of NULL.

Note that the appropriate statement would also include ISNULL(@String2,’EMPTY STRING2′), it has been avoided in the example to emphasize its importance at the @String1..

For more information on ISNULL look at Books Online link here

— Bru Medishetty

Leave a Reply