The solution below works one way: col1
words are removed from col2
.
Sample data
create table test
(
id int,
col1 nvarchar(max),
col2 nvarchar(max)
);
insert into test (id, col1, col2) values
(1, 'This is my test case', 'This is not my test Case, leave me alone');
Solution
with cte as
(
select t.id,
replace(s.value, ',', '') as word
from test t
cross apply string_split(t.col2, ' ') s
except
select t.id,
replace(s.value, ',', '')
from test t
cross apply string_split(t.col1, ' ') s
)
select string_agg(c.word, ' ') as result
from cte c
group by c.id;
Result
result
------------------
alone leave me not
Fiddle to see things in action with intermediate results.
New solution
Perhaps this version does not look so clean, but it should preserve the word order...
with cte as
(
select t.id,
row_number() over(order by (select null)) as sort,
replace(s.value, ',', '') as word
from test t
cross apply string_split(t.col2, ' ') s
where not exists ( select 'x'
from test t
cross apply string_split(t.col1, ' ') s2
where replace(s2.value, ',', '') = replace(s.value, ',', '') )
)
select string_agg(c.word, ' ') within group (order by c.sort) as result
from cte c
group by c.id;
New result
result
------------------
not leave me alone
New fiddle.