T-SQL substring - separating first and last name

前端 未结 11 1749
南方客
南方客 2020-11-30 05:50

I have a column which has FirstName and LastName together. I\'m writing a report to separate the FirstName And LastName. How do I get the FirstName and LastName separated in

11条回答
  •  一向
    一向 (楼主)
    2020-11-30 06:02

    For the last name as in US standards (i.e., last word in the [Full Name] column) and considering first name to include a possible middle initial, middle name, etc.:

    SELECT DISTINCT
                 [Full Name]
                ,REVERSE([Full Name])                   --  to visualize what the formula is doing
                ,CHARINDEX(' ', REVERSE([Full Name]))   --  finds the last space in the string
                ,[Last Name]    =   REVERSE(RTRIM(LTRIM(LEFT(REVERSE([Full Name]), CHARINDEX(' ', REVERSE([Full Name]))))))
                ,[First Name]   =   RTRIM(LTRIM(LEFT([Full Name], LEN([Full Name]) - CHARINDEX(' ', REVERSE([Full Name])))))
    

    FROM ...

    Note that this assumes [Full Name] has no spaces before or after the actual string. Otherwise, use RTRIM and LTRIM to remove these.

提交回复
热议问题