FirstName, LastName in SQL, too complex?

前端 未结 3 1430
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题