Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Comparing Name fields in same table

Author  Topic 

gems
Starting Member

19 Posts

Posted - 2014-11-29 : 09:59:04
Hi,

I have two name columns in my table, NAME1 & NAME2 that I want to compare to see if they match. Only problem is that the order of the first, last, middle name can be either same or different between the two fields.

For example
NAME1 = JAY JOHN SMITH
NAME2 = JOHN SMITH JAY or SMITH JOHN JAY

Is there a way to somehow reorder these fields and then compare using SQL?

Thanks a lot!

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-11-29 : 11:23:01
it is possible using the string splitter function and set operations

function: http://www.sqlservercentral.com/articles/Tally+Table/72993/

idea: use the string splitter on both name fields. You'll get two result sets. Compare the two using set ops. basically, if |A| = |B| = |A intersect B|, then the sets are equal
Go to Top of Page

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2014-11-29 : 14:13:58
Try this:
create table dbo.yourtable (
id int not null
,name1 varchar(80) null
,name2 varchar(80) null
,primary key (id)
);
insert into dbo.yourtable
values (1,'JAY JOHN SMITH','JOHN SMITH JAY')
,(2,'JAY JOHN SMITH','SMITH JOHN JAY')
,(3,'MR JAY JOHN SMITH','SMITH JOHN JAY')
;
with cte
as (select id
,1 as col
,case when charindex(' ',name1)>0
then substring(name1,1,charindex(' ',name1)-1)
else name1
end as name1
,case when charindex(' ',name1)>0
then substring(name1,charindex(' ',name1)+1,len(name1)-charindex(' ',name1))
else null
end as name2
from dbo.yourtable
union all
select id
,2 as col
,case when charindex(' ',name2)>0
then substring(name2,1,charindex(' ',name2)-1)
else name2
end as name2
,case when charindex(' ',name2)>0
then substring(name2,charindex(' ',name2)+1,len(name2)-charindex(' ',name2))
else null
end as name2
from dbo.yourtable
union all
select id
,col
,case when charindex(' ',name2)>0
then substring(name2,1,charindex(' ',name2)-1)
else name2
end as name1
,case when charindex(' ',name2)>0
then substring(name2,charindex(' ',name2)+1,len(name2)-charindex(' ',name2))
else null
end as name2
from cte
where name2 is not null
)
select *
from yourtable as a
where not exists (select *
from cte as b
left outer join cte as c
on c.id=b.id
and c.col=2
and c.name1=b.name1
where b.id=a.id
and b.col=1
and c.id is null
)
order by id
;
If you want records that matches (all words), leave the red "not", if you want records that doesn't match (all words), remove the red "not".
Go to Top of Page
   

- Advertisement -