Du bør virkelig gemme disse dele af navnet i separate kolonner (første normal form) for at undgå en sådan parsing.
Du kan lægge al logikken ind i et stort kald af indlejrede funktioner, men det er ret praktisk at adskille dem i enkelte kald ved hjælp af CROSS APPLY
.
Parsingen er ligetil:
- find kommaposition
- opdel strengen i en del før komma (
LastName
) og delenAfterComma
- find placeringen af det første mellemrum i den anden del
AfterComma
- opdeler strengen i to dele igen - dette giver
FirstName
og resten (AfterSpace
) - find pladsens position i
AfterSpace
- opdeler strengen i to dele igen - dette giver
Initial
ogSuffix
.
Forespørgslen kontrollerer også resultaterne af CHARINDEX
- den returnerer 0, hvis strengen ikke findes.
Det er klart, at hvis strengværdien ikke er i det forventede format, får du et forkert resultat.
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
resultat
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