December 25, 2008 at 11:45 pm
hi ,
In the source Field PATNAME data look likes
John,David Robert
sustaita,corie m
pena,geneva jesus
i want output splitted in to 3 fields(with out vb script )like
Field1 Field2 Field3
john David Robert
sustaita Corie m
pena geneva jesus
December 26, 2008 at 12:16 am
create table #patname
(
FullName varchar(100),
FirstName varchar(100),
MiddleName varchar(100),
LastName varchar(100)
)
insert into #patname(FullName)
select 'John,David Robert'
UNION ALL
select 'sustaita,corie m'
UNION ALL
select 'pena,geneva jesus'
-- Assumption, the field full name contains last name, a comma, first name, a space and middle name
update #patname
set lastName=left(fullname, charindex(',', fullname)-1),
firstName=substring(fullname, charindex(',', fullname)+1,charindex(' ', fullname)-charindex(',', fullname)-1),
middleName=right(fullName, len(fullName)-charindex(' ', fullname))
from #patname
select * from #patname
output
----------
FullName FirstName MiddleName LastName
John,David RobertDavid Robert John
sustaita,corie mcorie m sustaita
pena,geneva jesusgeneva jesus pena
December 26, 2008 at 1:24 am
December 26, 2008 at 11:29 am
Using the test data nicely provided by Pradeep, with an added row...
create table #patname
(
FullName varchar(100),
FirstName varchar(100),
MiddleName varchar(100),
LastName varchar(100)
)
insert into #patname(FullName)
select 'John,David Robert'
UNION ALL
select 'sustaita,corie m'
UNION ALL
select 'pena,geneva jesus'
UNION ALL
SELECT 'Moden,Jeff'
... we can make it so that a middle name is not required. Still, it won't handle names like "St. James, Timothy R" as it is, but it gets you closer...
SELECT FullName,
CASE WHEN PARSENAME(FullName,3) IS NULL
THEN PARSENAME(FullName,1)
ELSE PARSENAME(FullName,2)
END AS First,
CASE WHEN PARSENAME(FullName,3) IS NULL
THEN NULL
ELSE PARSENAME(FullName,1)
END AS Middle,
CASE WHEN PARSENAME(FullName,3) IS NULL
THEN PARSENAME(FullName,2)
ELSE PARSENAME(FullName,3)
END AS Last
FROM (
SELECT REPLACE(REPLACE(FullName,',','.'),' ','.') AS FullName
FROM #patname
)d
--Jeff Moden
Change is inevitable... Change for the better is not.
December 26, 2008 at 12:10 pm
Jeff, I must say the way you play around with T-SQL is really amazing. Atleast I couldnt think of using PARSENAME in this example:w00t:
December 26, 2008 at 12:58 pm
ps (12/26/2008)
Jeff, I must say the way you play around with T-SQL is really amazing. Atleast I couldnt think of using PARSENAME in this example:w00t:
:blush: That's awfully nice of you to say... Thanks Pradeep.
The real fact is, the use of CHARINDEX, like you did, is probably a lot faster because I had to use a double nested REPLACE to get mine to work. Just wanted to show a different way.
I'm thinking that RegEx would be much better at splitting names...
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 6 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply