I was trying to extract the lastName, firstName, middleName from Name column which contains whole name format.
here's the sample names which I'm trying to extract:
DELA CRUZ, JUAN PONCE SR. ENRILE
ATIENZA, ROBERTO JR. SANTO
GONZA, MARK ANTHONY, DELLY-LO
I want to extract them like these:
LastName | FirstName | MiddleName
DELA CRUZ | JUAN PONCE SR. | ENRILE
ATIENZA | ROBERTO JR. | SANTOS
GONZA | MARK ANTHONY | DELLY
This is my script so far
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
I also having a problem when extracting middle with -LO suffix.
thank you
Try this below logic (modified your one)
DECLARE @Name VARCHAR(50) = 'DELA CRUZ, JUAN PONCE SR. ENRILE'
SELECT
SUBSTRING(@Name, 0, CharIndex(',', @Name)) LastName,
REVERSE(SUBSTRING(REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name))), 0, CharIndex(' ', REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name)))))) MiddleName,
REPLACE(REVERSE(RIGHT(REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name))),LEN(REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name))))-CharIndex(' ', REVERSE(RIGHT(@Name,LEN(@Name)-CharIndex(',', @Name))))+1)),',','') FirstName
String operations are a real pain in SQL Server. I recommend using APPLY
to define intermediate values, if you have to use them:
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 is a db<>fiddle.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.