我想知道是否有人可以提供一种简单的方法将名称提取到不同的列中,如下所示。在名字,中间名和后缀之间的姓氏和空格后面有一个逗号。非常感谢。
存储数据:
Name
Walker,James M JR
Smith,Jack P
Smith,Whitney
必填结果:
LastName FirstName Suffix
Walker James JR
Smith Jack
Smith Whitney
尝试过的代码:
select top 5 Name,
LEFT(Name, CHARINDEX(',', Name) - 1) AS LastName,
right(Name, len(Name) - CHARINDEX(',', Name)) as FirstName
将First Name与Middle Initial和Suffix分开时遇到问题。然后从右边的最后一个空格获得后缀。
答案 0 :(得分:0)
您确实应该将名称的这些部分存储在单独的列(第一个普通表单)中,以避免这种解析。
您可以将所有逻辑放入一个嵌套函数的大调用中,但使用CROSS APPLY
将它们分成单个调用非常方便。
解析很简单:
LastName
)和部分AfterComma
AfterComma
FirstName
,其余部分(AfterSpace
)AfterSpace
Initial
和Suffix
。查询还检查CHARINDEX
的结果 - 如果找不到字符串,则返回0.
显然,如果字符串值不是预期的格式,您将得到不正确的结果。
DECLARE @T TABLE (Name varchar(8000));
INSERT INTO @T (Name) VALUES
('Walker'),
('Walker,James M JR'),
('Smith,Jack P'),
('Smith,Whitney');
SELECT
Name
,LastName
,AfterComma
,FirstName
,AfterSpace
,MidInitial
,Suffix
FROM
@T
CROSS APPLY (SELECT CHARINDEX(',', Name) AS CommaPosition) AS CA_CP
CROSS APPLY (SELECT CASE WHEN CommaPosition > 0 THEN
LEFT(Name, CommaPosition - 1) ELSE Name END AS LastName) AS CA_LN
CROSS APPLY (SELECT CASE WHEN CommaPosition > 0 THEN
SUBSTRING(Name, CommaPosition + 1, 8000) ELSE '' END AS AfterComma) AS CA_AC
CROSS APPLY (SELECT CHARINDEX(' ', AfterComma) AS SpacePosition) AS CA_SP
CROSS APPLY (SELECT CASE WHEN SpacePosition > 0 THEN
LEFT(AfterComma, SpacePosition - 1) ELSE AfterComma END AS FirstName) AS CA_FN
CROSS APPLY (SELECT CASE WHEN SpacePosition > 0 THEN
SUBSTRING(AfterComma, SpacePosition + 1, 8000) ELSE '' END AS AfterSpace) AS CA_AS
CROSS APPLY (SELECT CHARINDEX(' ', AfterSpace) AS Space2Position) AS CA_S2P
CROSS APPLY (SELECT CASE WHEN Space2Position > 0 THEN
LEFT(AfterSpace, Space2Position - 1) ELSE AfterSpace END AS MidInitial) AS CA_MI
CROSS APPLY (SELECT CASE WHEN Space2Position > 0 THEN
SUBSTRING(AfterSpace, Space2Position + 1, 8000) ELSE '' END AS Suffix) AS CA_S
<强>结果强>
Name LastName AfterComma FirstName AfterSpace MidInitial Suffix
Walker Walker
Walker,James M JR Walker James M JR James M JR M JR
Smith,Jack P Smith Jack P Jack P P
Smith,Whitney Smith Whitney Whitney