1

Below is my table,

create table t(
   id int,
   colParam varchar(max))

insert into t values(1,'["param1", "param2"]')
insert into t values(2,'["param2"]')
insert into t values(3,'["param1"]')
insert into t values(4,'["param2", "param3"]')
insert into t values(5,'["param1", "param2"]')

tried

declare @str varchar(max) = 'param1'; Select * from t where colParam like '%'+ @str+'%'

its not working for

declare @str varchar(max) = 'param1,param2'; Select * from t where colParam like '%'+ @str+'%'

i want to select rows by passing colPar as 'param1,param2' so it will result me all the records containing param1 and param2 in colParam

2
  • So based on your sample data it should return only ID=1 and 5? Commented Dec 12, 2019 at 7:25
  • No, i should return all, because param1 and param2 exists in all records. When i say param3 it should return Id =4, on param1 it should return Id =1,3,5 Commented Dec 12, 2019 at 8:05

2 Answers 2

1

This quiet tricky.

create table #t(
    id int,
    colParam varchar(max)
)

insert into #t values(1,'["param1", "param2"]')
insert into #t values(2,'["param2"]')
insert into #t values(3,'["param1"]')
insert into #t values(4,'["param2", "param3"]')
insert into #t values(5,'["param1", "param2"]')

declare @str varchar(max) = 'param1,param2';     

to Return all matching values.

select distinct id, t1.colParam  from #t t1
cross apply string_split(t1.colParam, ',') t2
cross apply string_split(@str, ',') t3
where t2.value like '%'+t3.value+'%'

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

I tried with the cross apply before but used only once in query. Your efforts solved my query and time. Thank you.
1

If you are using SQL Server 2016 and above, then you can use STRING_SPLIT.

As MSDN says:

A table-valued function that splits a string into rows of substrings, based on a specified separator character.

So your can look like this:

DECLARE @t TABLE
(
    id int,
    colParam varchar(max)
)

insert into @t values(1,'["param1", "param2"]')
insert into @t values(2,'["param2"]')
insert into @t values(3,'["param1"]')
insert into @t values(4,'["param2", "param3"]')
insert into @t values(5,'["param1", "param2"]')

SELECT 
  t.id
, s.col
FROM @t AS t
OUTER APPLY
(
    SELECT 
    spl.value AS col
    FROM STRING_SPLIT(
        (SELECT _t.colParam FROM @t AS _t WHERE _t.id = t.id), ',') AS spl
 )s

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.