https://www.mssqltips.com/sqlservertip/2985/concatenate-sql-server-columns-into-a-string-with-concat/
SELECT Title, FirstName, MiddleName, LastName, Title + ' ' + FirstName + ' ' + MiddleName + ' ' + LastName as MailingName FROM Person.Person
As you can see in the screen shot below the MailingName is NULL for any row that has NULL for any one of the name columns. The only rows that have MailingName filled in have a value for all the title, firstname, middlename, and lastname columns. This could be corrected by wrapping ISNULL(column,'') around all the columns in the concatenated field to account for any values having nulls, but that code gets long, messy, and hard to read.

Below is an example is using ISNULL along with the plus sign for concatenation. The ISNULL function will replace NULL values with the value noted in the second parameter, which in this example is an empty string.
SELECT Title, FirstName, MiddleName, LastName, ISNULL(Title,'') + ' ' + ISNULL(FirstName,'') + ' ' + ISNULL(MiddleName,'') + ' ' + ISNULL(LastName,'') as MailingName FROM Person.Person
As you can see in the example below, the MailingName is no longer NULL as it replaced the NULL values with an empty string. This achieves the same as using the CONCAT() function, but requires a lot more code and readability.

The next set of code is using the new CONCAT() function that is in SQL Server 2012 and later versions. It replaces NULL values with an empty string of type VARCHAR(1). This code is much easier to read and write when you need to have NULL code handling in place.
SELECT Title, FirstName, MiddleName, LastName, CONCAT(Title,' ',FirstName,' ',MiddleName,' ',LastName) as MailingName FROM Person.Person
If you see the results of this, all MailingName values are present, even if they have some of the columns set to NULL.

As you can see this new function is very handy and behaves much different that the old form of concatenation. Instead of evaluating to NULL if any if the columns cont
No comments:
Post a Comment