我试图从包含全名格式的“名称”列中提取姓氏、名字、中间名。
这是我尝试提取的示例名称:
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 后缀的中间时也遇到问题。
谢谢
最佳答案
字符串操作在 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);
Here是一个数据库<> fiddle 。
关于sql - 从字符串中提取部分名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60968311/