簡體   English   中英

從字符串中提取部分名稱

[英]Extracting part of name from string

我試圖從包含全名格式的 Name 列中提取 lastName、firstName、middleName。

這是我試圖提取的示例名稱:

DELA CRUZ, JUAN PONCE SR. ENRILE
ATIENZA, ROBERTO JR. SANTO
GONZA, MARK ANTHONY, DELLY-LO

我想像這樣提取它們:

    LastName    | FirstName       | MiddleName
    DELA CRUZ   | JUAN PONCE SR.  | ENRILE
    ATIENZA     | ROBERTO JR.     | SANTOS
    GONZA       | MARK ANTHONY    | DELLY

到目前為止,這是我的腳本

DECLARE @Name    VARCHAR(50) = 'DELA CRUZ, JUAN PONCE SR. ENRILE'

SELECT
SUBSTRING(@Name, 0, CharIndex(',', @Name)) LastName,
REVERSE(LEFT(REVERSE(@Name), CharIndex(' ', reverse(@Name))-1)) MiddleName

我在使用 -LO 后綴提取中間時也遇到問題。

謝謝你

試試下面的邏輯(修改你的)

DECLARE @Name    VARCHAR(50) = 'DELA CRUZ, JUAN PONCE SR. ENRILE'

SELECT
SUBSTRING(@Name, 0, CharIndex(',', @Name)) LastName,
REVERSE(SUBSTRING(REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name))), 0, CharIndex(' ', REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name)))))) MiddleName,
REPLACE(REVERSE(RIGHT(REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name))),LEN(REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name))))-CharIndex(' ', REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name))))+1)),',','') FirstName         

字符串操作在 SQL Server 中是一個真正的痛點。 如果您必須使用它們,我建議使用APPLY來定義中間值:

select v1.lastname, rest, 
       (case when v1.rest like '%,%'
             then left(rest, charindex(',', rest) - 1)
             else left(rest, len(rest) - charindex(' ', reverse(rest)))
        end) as firstname,
       (case when v1.rest like '%,%'
             then stuff(rest, 1, charindex(',', rest) + 1, '')
             else stuff(rest, 1, len(rest) - charindex(' ', reverse(rest)) + 1, '')
        end) as lastname
from t cross apply
     (values (left(names, charindex(',', names) - 1), stuff(names, 1, charindex(',', names) + 1, ''))
     ) v1(lastname, rest);

是一個 db<>fiddle。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM