exercise in futility. this will fail guaranteed with any possibility of data delimiters. get your data in order otherwise you will need this type of cirque du soleil gymnastics to sort things out.
Below code NOT RECOMMENDED !
create table #sample(id int identity(1,1), LastName nvarchar(50), TeacherD varchar(50))
insert into #sample
select 'corbly-tip', 'corbly, annette b' union
select 'baker-hage', 'cubs - bakerhage - 8c' union
select 'king grie', 'king, bev'
create table #lastnames(id int, lastname varchar(50))
create table #teacherDs(id int, teacherD varchar(50))
create table #clean_sample(id int, LastName nvarchar(50), TeacherD varchar(50), LastNameClean nvarchar(50), TeacherDClean varchar(50))
insert into #clean_sample
select id, LastName, TeacherD, replace(replace(lastname,',',' '),'-',' '), replace(replace(TeacherD,',',' '),'-',' ') from #sample
;with details
as
(
SELECT A.id,
Split.a.value('.', 'VARCHAR(100)') AS Data
FROM
(
SELECT id,
cast(REPLACE('<r>' + LastNameClean + '</r>', SPACE(1), '</r><r>') as xml) as Data
FROM #clean_sample
) AS A CROSS APPLY Data.nodes ('/r') AS Split(a)
)
insert into #lastnames
select a.id,
b.Data as lastname
from #clean_sample a
join details b on a.id = b.id
;with details
as
(
SELECT A.id,
Split.a.value('.', 'VARCHAR(100)') AS Data
FROM
(
SELECT id,
cast(REPLACE('<r>' + TeacherDClean + '</r>', SPACE(1), '</r><r>') as xml) as Data
FROM #clean_sample
) AS A CROSS APPLY Data.nodes ('/r') AS Split(a)
)
insert into #teacherDs
select a.id,
b.Data as teacherD
from #clean_sample a
join details b on a.id = b.id
where b.Data <> ''
--select * From #clean_sample
--create table #lastnames(id int, lastname varchar(50))
--insert into #lastnames
--;with cte
--as
--(
--select id,
-- cast(REPLACE('<r>' + LastNameClean + '</r>', SPACE(1), '</r><r>') as xml) as snap
-- From #clean_sample
--)
--select snap.value('(/r)[text]', 'varchar(50)') as lastname
--from cte
select distinct s.*
from #sample s
join #lastnames ln on s.id = ln.id
join #teacherDs td on s.id = td.id
where s.lastname like '%' + ln.lastname + '%'
or s.TeacherD like '%' + td.teacherD + '%'
--select * from #teacherDs
drop table #sample
drop table #clean_sample
drop table #lastnames
drop table #teacherDs