FirstName, LastName in SQL, too complex?

前端 未结 3 1391
無奈伤痛
無奈伤痛 2021-01-01 05:07

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,\'\')+
                


        
相关标签:
3条回答
  • 2021-01-01 05:38

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

    SELECT Isnull(LastName,'') + ', ' + Isnull(FirstName,'')
    FROM Person
    
    0 讨论(0)
  • 2021-01-01 05:45

    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.

    0 讨论(0)
  • 2021-01-01 05:45

    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.

    0 讨论(0)
提交回复
热议问题