Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the shortest TSQL to concatenate a person's name which may contain nulls

3 fields: FirstName, MiddleName, LastName

Any field can be null, but I don't want extra spaces. Format should be "First Middle Last", "First Last", "Last", etc.

like image 516
Keith Walton Avatar asked Nov 27 '22 16:11

Keith Walton


1 Answers

    LTRIM(RTRIM(
    LTRIM(RTRIM(ISNULL(FirstName, ''))) + ' ' + 
    LTRIM(RTRIM(ISNULL(MiddleName, ''))) + ' ' + 
    LTRIM(ISNULL(LastName, ''))
    ))

NOTE: This won't leave trailing or leading spaces. That's why it's a little bit uglier than other solutions.

like image 140
Andrew Rollings Avatar answered Dec 10 '22 03:12

Andrew Rollings