开发者

FirstName, LastName in SQL, too complex?

This SQL seems complex, is there an easier wa开发者_Python百科y 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


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.


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

SELECT Isnull(LastName,'') + ', ' + Isnull(FirstName,'')
FROM Person
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜