tags:

views:

349

answers:

2

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,'')+
       CASE WHEN LastName+FirstName IS NOT NULL THEN ', ' END+
       COALESCE(FirstName,'') AS Name
FROM Person
+9  A: 

How about

SELECT COALESCE(LastName + ', ' + FirstName, 
                LastName, 
                FirstName) Name
FROM Person
Charles Bretana
Nice. I like it. Seems so obvious now.
Hogan
Actually, you forgot one:COALESCE(LastName + ', ' + FirstName, LastName, FirstName, 'This poor sucker has no name')Just kidding, of course.
Stu
Would this work since you are putting a comma in the coalesce? I might have just learned something new if it does work, but I would think that there would never be a chance for this to be NULL.
Dusty
When you concatenate a string to a null string in TSQL you get null. The string constant goes to null in the first argument if either is null.
Hogan
Well then I learned something. :) Thanks
Dusty
A: 

I don't think this is complex at all... On MSSQL you can do something like

SELECT Isnull(LastName,'') + ', ' + Isnull(FirstName,'')
FROM Person
mRt
This would return a comma if the names are null which I think is poor. I won't downvote it, but won't upvote it either. :)
Dusty
This does not work... you get results like "Frist, " and ", Last"
Hogan
Sorry, but in the question the user do not specify it.
mRt
@mRt, really? You would output hanging commas in your code because someone did not specify it?
Hogan
I don't know. I just post an example where I use the Isnull().
mRt
It's clear from the original post that the developer was interesting covering cases where one of the values might be null.
jpierson