Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two column values which are comma separated values?

I have one table with specific columns, in that there is a column which contains comma separated values like test,exam,result,other.

I will pass a string like result,sample,unknown,extras as a parameter to the stored procedure. and then I want to get the related records by checking each and every phrase in this string.

For Example:

TableA

ID        Name                Words
1         samson              test,exam,result,other
2         john                sample,no query
3         smith               tester,SE

Now I want to search for result,sample,unknown,extras

Then the result should be

ID        Name                Words
1         samson              test,exam,result,other
2         john                sample,no query

because in the first record result matched and in the second record sample matched.

like image 704
Srikanth Avatar asked Mar 01 '23 03:03

Srikanth


1 Answers

That's not a great design, you know. Better to split Words off into a separate table (id, word).

That said, this should do the trick:

set nocount on
declare @words varchar(max) = 'result,sample,unknown,extras'

declare @split table (word varchar(64))
declare @word varchar(64), @start int, @end int, @stop int

-- string split in 8 lines
select @words += ',', @start = 1, @stop = len(@words)+1
while @start < @stop begin
  select
    @end   = charindex(',',@words,@start)
  , @word  = rtrim(ltrim(substring(@words,@start,@end-@start)))
  , @start = @end+1
  insert @split values (@word)
end

select * from TableA a
where exists (
  select * from @split w
  where charindex(','+w.word+',',','+a.words+',') > 0
  )

May I burn in DBA hell for providing you this!

Edit: replaced STUFF w/ SUBSTRING slicing, an order of magnitude faster on long lists.

like image 174
Peter Radocchia Avatar answered Mar 03 '23 04:03

Peter Radocchia