我正在尝试将名称字段分隔到相应的字段中。名称字段不一致。它可以显示为 Doe III,John w 或 Doe,John,或 Doe III,John,或 Doe,John W 或者可能缺少后缀和/或中间首字母。任何想法将不胜感激。
SELECT (
CASE LEN(REPLACE(FirstName, ' ', ''))
WHEN LEN(FirstName + ' ') - 1
THEN PARSENAME(REPLACE(FirstName, ' ', '.'), 2)
ELSE PARSENAME(REPLACE(FirstName, ' ', '.'), 3)
END
) AS LastName
,(
CASE LEN(REPLACE(FirstName, ' ', ''))
WHEN LEN(FirstName + ',') - 1
THEN NULL
ELSE PARSENAME(REPLACE(FirstName, ' ', '.'), 2)
END
) AS Suffix
,PARSENAME(REPLACE(FirstName, ' ', '.'), 1) AS FirstName
FROM Trusts.dbo.tblMember
如上所述,无论格式如何,我都需要使用名称来解析LastName,Suffix,FirstName,MiddleInitial的相应字段,无论它是否具有后缀或中间的首字母
答案 0 :(得分:0)
如果给定的4个名称是唯一的案例类型,那么您可以使用类似下面的内容。
注意:我使用CTE表tbl2
来区分comma_pos
,first_space
,second_space
,以便更好地理解主查询。您可以将主查询中的这些值替换为CTE中的相应函数,以使主查询更快。我的意思是在主查询中用comma_pos
替换charindex(',',name)
,依此类推。
此外,我假设name
列中没有前导/尾随或额外的空格或任何垃圾字符。如果有,请在继续之前先清理数据。
with tbl2 as (
select tbl.*,
charindex(',',name) as comma_pos,
charindex(' ',name,1) first_space,
charindex(' ',name,charindex(' ',name,1)+1) second_space
from tbl)
select tbl2.name
,case when second_space <> 0
then substring(name,comma_pos+1,second_space-comma_pos-1)
when first_space > comma_pos
then substring(name,comma_pos+1,first_space-comma_pos-1)
else substring(name,comma_pos+1,len(name)-comma_pos)
end as first_name
,case when second_space <> 0
then substring(name,second_space+1,len(name)-second_space)
when first_space > comma_pos
then substring(name,first_space+1,len(name)-first_space)
end as middle_name
,case when first_space=0 or first_space>comma_pos
then substring(name,1,comma_pos-1)
else substring(name,1,first_space-1)
end as last_name
,case when first_space=0 or first_space>comma_pos
then null
else substring(name,first_space,comma_pos-first_space)
end as suffix
from tbl2;