This SQL seems complex, is there an easier way to get FirstName, LastName when one or both of the fields can be NULL?
SELECT COALESCE(LastName,\'\')+
I don't think this is complex at all... On MSSQL you can do something like
SELECT Isnull(LastName,'') + ', ' + Isnull(FirstName,'')
FROM Person
How about
SELECT COALESCE(LastName + ', ' + FirstName,
LastName, FirstName) Name
FROM Person
if firstname
or lastname
is null the entire first expression (with the ,
), becomes null, forcing the coalesce to examine, second, the lastname
alone, and then if lastname
is null, finally, the firstname
alone.
You can precalculate this in a table by using a peristed calculated column if you will be using this form of the name often. The column could even be indexed if you needed it to be.
ALTER TABLE A
ADD [person_name_last_first] AS COALESCE(LastName + ', ' + FirstName,
LastName, FirstName) PERSISTED
The biggest advantage is that you never have to write this piece of code again, names will be consistently displayed and that you only use the databases time to perform this action when the first and last names are added or changed.