Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FirstName, LastName in SQL, too complex?

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
like image 243
Hogan Avatar asked Dec 22 '22 07:12

Hogan


1 Answers

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.

like image 142
Charles Bretana Avatar answered Jan 02 '23 06:01

Charles Bretana