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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With