Brian's Blog

items I see across my tribes

SQL Null: String Concatenation

October 02
by briancarter 2. October 2010 08:27

image[1] This week, while searching for a bug, I came across a common issue.  Many layers down in the code, a stored procedure was called.  The SP concatenated 2 columns, which allowed null values.  The majority of the time, empty string was given as default.  Some new code, placed null in one but not both fields.

Because Null is not a data value, but a marker for unknown value, using string concatenation operators on Null results in an unknown value, which is represented by Null.  In the following example, concatenating the string values shows how this can cause issues:

DECLARE @str1 VARCHAR(100)
DECLARE @str2 VARCHAR(100)
DECLARE @str3 VARCHAR(100)

SET @str1 = 'Hello'
SET @str2 = NULL
SET @str3 = 'World'

-- Nulls concatenated with anything is Null
SELECT @str1 + @str2 + @str3

-- Use ISNULL to change Nulls to empty strings before concatenation
SELECT Isnull(@str1, '') + Isnull(@str2, '') + Isnull(@str3, '') 

The 1st Select results in a return value of: NULL

The 2nd Select results what we expected: HelloWorld

If your database structure allows nulls and you use the columns in a concatenation (+), even if your code defaults to empty string, avoid future mishaps by including the ISNULL function.

Categories:


 Questions or Feedback, my contact information is located on my About page.


The opinions, thoughts, and comments made in these blog posts are solely my own (unless otherwise stated). They do not reflect the opinions, thoughts or practices of my employer, my universities, my family, or anyone else. Also, I retain the right to change my mind about anything I publish here without having to go back and edit posts that occurred in the past. 

These are my opinions, or just as likely, someone else's opinions that I leveraged for my own.