简体   繁体   English

如何在SQL中将名称拆分为名字和姓氏

[英]how to split name into first and last name in SQL

I have a table that contain first name and last name as below 我有一个包含名字和姓氏的表,如下所示

First_Name LAST_NAME

John       Milano
Garry      Sanders 
           Barr, Jerome P
           Venti, Louis 

I need to correct some rows which has complete name in the column Last_name. 我需要更正在Last_name列中具有完整名称的某些行。 My desired output is:- 我想要的输出是:-

First_Name LAST_NAME

John       Milano
Garry      Sanders 
Jerome     Barr
Louis      Venti

Thanks in advance! 提前致谢!

This will get you close, with a couple caveats: 1) Some first names have two words -- "Mary Ann", etc. So, you probably want to keep those. 请注意以下几点:1)一些名字有两个词-“ Mary Ann”,等等。因此,您可能希望保留这些名字。 2) You only want to change rows where the LAST_NAME column contains a comma. 2)您只想更改LAST_NAME列包含逗号的行。

UPDATE MyTable
    SET First_Name = LTRIM(SUBSTRING(LAST_NAME, CHARINDEX(',', LAST_NAME) + 1, 100)),
        LAST_NAME = LTRIM(RTRIM(SUBSTRING(@name, 0, CHARINDEX(',', @name))))
WHERE CHARINDEX(',', LAST_NAME) > 0

So, you will have "Jerome P" as the first name still. 因此,您仍将“ Jerome P”作为名字。 If you want to restrict first names to a single word, you would have to do a bit more. 如果要将名字限制为一个单词,则需要做更多的工作。 This should work: 这应该工作:

UPDATE MyTable
    SET First_Name = LTRIM(RTRIM(SUBSTRING(@name, 0, CHARINDEX(' ', @name))))
WHERE CHARINDEX(' ', First_Name) > 0

You can use a case expression with CHARINDEX and LEFT 您可以将案例表达式与CHARINDEXLEFT

select
    First_Name 
    ,case
         when charindex(',',LAST_NAME) > 1 then left(LAST_NAME,charindex(',',LAST_NAME) - 1)
         else LAST_NAME
     end as LAST_NAME
From YourTable

Example

declare @var varchar(64) = 'Barr, Jerome P'

select 
case
    when charindex(',',@var) > 1 then left(@var,charindex(',',@var) - 1)
    else @var
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM