I am working on a Microsoft SQL Server 2005 with Transact-SQL.
I am trying to concatenate string values coming from different columns of the same table dealing with NULL values.
Say for example the table is Person and the columns are FirstName, SurnamePrefix, LegalSurname
It happened that concatenating a string value with a NULL value (coming from two different columns) returns in output a NULL value.
I tried different scenarios to prevent NULL values in output:
- Starting from:
Person.FirstName + ' ' + COALESCE(RTRIM(LTRIM(Person.SurnamePrefix)) + ' ', '') + Person.LegalSurname
- I changed my statement to:
COALESCE(Person.FirstName + ' ', '') + COALESCE(Person.SurnamePrefix, '') + COALESCE(' ' + Person.LegalSurname, '')
Then I came across functions like ISNULL(), NULLIF() etc.
Which is the best and efficient approach to show empty strings values in output rather than NULL values?
Is the solution affected by the version of the SQL Server? (i.e. 2005, 2008, etc.)
ISNULLis good for default values, as you are doing.COALESCEhas the advantage of accepting more than two arguments.NULLIFis quite different as it returns aNULLif the arguments are equal.You can benchmark them for performance. I suspect that the difference is negligible and that it is far more important to opt for clarity in your code.