如何从示例中提取firstname,middlename和lastname。
格式
FirstName,LastName OptionalMiddleNameOrInitial
示例数据
JAMES,BEVERLY B
MARS,CLARENCE
MCCOY,JANE A
FERN,GAIL MAY
rtrim(ltrim(substring(NAME,1,CHARINDEX(',',NAME)-1))) AS LastName
ltrim(ltrim(substring(NAME,CHARINDEX(',',NAME)+2, len(NAME)))) AS FirstName
答案 0 :(得分:1)
我想通了
SUBSTRING((SUBSTRING(p.name, CHARINDEX(' ', p.name) + 1, 8000)), 1, CHARINDEX(' ', (SUBSTRING(p.name, CHARINDEX(' ', p.name) + 1, 8000))) - 1)as[PatientLastName]
case
when LEN(LTRIM(rtrim(p.name))) - LEN(replace(ltrim(rtrim(p.name)),' ','')) = 2
then REVERSE(SUBSTRING(REVERSE(LTRIM(RTRIM(p.name))),1,CHARINDEX(' ',REVERSE(LTRIM(RTRIM(p.name))))))
else ''end as[PatientMiddleName]
,Replace(LEFT(p.Name,CHARINDEX(' ',p.Name)-1),',','') as PatientFirstName
答案 1 :(得分:0)
我认为你会觉得这很有用。
create table #temp
(
FULLNAME VARCHAR(100),
ID INT
)
INSERT INTO #TEMP VALUES ('TUCKER, KEVIN G', 1)
INSERT INTO #TEMP VALUES ('SCOTT, JOHN', 2)
INSERT INTO #TEMP VALUES ('ERIC, T W', 3)
INSERT INTO #TEMP VALUES ('MUNICH, SMITH D', 4)
INSERT INTO #TEMP VALUES ('LYOD SR, CLIVE G', 5)
INSERT INTO #TEMP VALUES ('HANSEN JR, CHARLES S', 6)
INSERT INTO #TEMP VALUES ('BROWN,SHERMAN', 7)
INSERT INTO #TEMP VALUES ('ANDREWS III, CLARK A', 8)
INSERT INTO #TEMP VALUES ('MAMMTAN, MARY LOU', 9)
DECLARE @Suffixes TABLE(
Suffix VARCHAR(5)
)
INSERT INTO @Suffixes
VALUES ('I'),
('II'),
('III'),
('IV'),
('V'),
('SR'),
('JR'),
('1st'),
('2nd'),
('3rd')
SELECT T.id,
T.Fullname,
F7.*,
F4.[LAST Name],
F4.Suffix
FROM #temp T
CROSS APPLY (SELECT LEFT(T.FullName,CHARINDEX(',',T.FULLNAME + ',') - 1) AS cLastName,
LTRIM(SUBSTRING(T.FullName,CHARINDEX(',',T.FULLNAME + ',') + 1,
LEN(T.FullName))) AS cFirstName) F1
CROSS APPLY (SELECT LEFT(F1.cLastName,CHARINDEX(' ',F1.cLastName + ' ') - 1) AS LName,
SUBSTRING(F1.cLastName,CHARINDEX(' ',F1.cLastName + ' ') + 1,
LEN(F1.cLastName)) AS pSuffix) F2
CROSS APPLY (SELECT CASE
WHEN LEN(pSuffix) > 0
AND EXISTS (SELECT 1
FROM @Suffixes S
WHERE S.Suffix = pSuffix) THEN 'Y'
ELSE 'N'
END AS SuffixExists) F3
CROSS APPLY (SELECT CASE
WHEN F3.SuffixExists = 'Y' THEN F2.LName
ELSE RTRIM(F2.LName + ' ' + F2.pSuffix)
END AS [LAST Name],
CASE
WHEN F3.SuffixExists = 'Y' THEN F2.pSuffix
ELSE ''
END AS [Suffix]) F4
CROSS APPLY (SELECT LEFT(F1.cFirstName,CHARINDEX(' ',F1.cFirstName + ' ') - 1) AS FName,
SUBSTRING(F1.cFirstName,CHARINDEX(' ',F1.cFirstName + ' ') + 1,
LEN(F1.cFirstName)) AS MInitial) F5
CROSS APPLY (SELECT CASE
WHEN LEN(MInitial) = 1 THEN 'Y'
ELSE 'N'
END AS MIExists) F6
CROSS APPLY (SELECT CASE
WHEN F6.MIExists = 'Y' THEN F5.FName
ELSE RTRIM(F5.FName + ' ' + F5.MInitial)
END AS [FIRST Name],
CASE
WHEN F6.MIExists = 'Y' THEN F5.MInitial
ELSE ''
END AS [Middle Initial]) F7
http://blogs.lessthandot.com/index.php/datamgmt/datadesign/parsing-fullname-field-to-individual/