SQL: parse the first, middle and last name from a fullname field

后端 未结 23 1673
粉色の甜心
粉色の甜心 2020-11-27 10:47

How do I parse the first, middle, and last name out of a fullname field with SQL?

I need to try to match up on names that are not a direct match on full name. I\'d

23条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 11:40

    Based on @hajili's contribution (which is a creative use of the parsename function, intended to parse the name of an object that is period-separated), I modified it so it can handle cases where the data doesn't containt a middle name or when the name is "John and Jane Doe". It's not 100% perfect but it's compact and might do the trick depending on the business case.

    SELECT NAME,
    CASE WHEN parsename(replace(NAME, ' ', '.'), 4) IS NOT NULL THEN 
       parsename(replace(NAME, ' ', '.'), 4) ELSE
        CASE WHEN parsename(replace(NAME, ' ', '.'), 3) IS NOT NULL THEN 
        parsename(replace(NAME, ' ', '.'), 3) ELSE
       parsename(replace(NAME, ' ', '.'), 2) end END as FirstName
       ,
    CASE WHEN parsename(replace(NAME, ' ', '.'), 3) IS NOT NULL THEN 
       parsename(replace(NAME, ' ', '.'), 2) ELSE NULL END as MiddleName,
       parsename(replace(NAME, ' ', '.'), 1) as LastName
    from  {@YourTableName}
    

提交回复
热议问题