Reputation: 4941
In my SQL Server table, there is a column in which I have comma separated values.
For example: in column AllSegmentsList
and the values in the column are like 'a, b, c,d, e'
.
Now, I my query I want to say
select *
from table
if one of the the entries out of all the comma separated values in that column is 'b'
but I want to make sure that the query can handle spaces on either sides of commas, if are present(not always).
Upvotes: 0
Views: 169
Reputation: 10875
this should work in all cases:
select * from tablename where replace(replace(','+allsegmentslist+',',', ',','),' ,',',') like '%,b,%'
Upvotes: 2
Reputation: 352
It kind of depends on your data. If no value contains a space, following should work
select
*
from
table
where
replace(concat(',', slist, ','), ' ', '') like '%,b,%';
Upvotes: 1
Reputation: 118947
If you are fine with finding only substrings, this will do:
SELECT *
FROM tablename
WHERE allsegmentslist like '%b%'
However if you need to search for the full length text and not substring, this will work:
SELECT *
FROM tablename
WHERE allsegmentslist like '%b,%'
OR allsegmentslist like '%,b%'
OR allsegmentslist like '%,b,%'
OR allsegmentslist = 'b'
If there are spaces after the commas, you will need to change to this:
SELECT *
FROM tablename
WHERE allsegmentslist like '%b,%'
OR allsegmentslist like '%, b%'
OR allsegmentslist like '%, b,%'
OR allsegmentslist = 'b'
Alternatively if the commas only sometimes have spaces after them, you will need this:
SELECT *
FROM tablename
WHERE allsegmentslist like '%b,%'
OR allsegmentslist like '%,b%'
OR allsegmentslist like '%,b,%'
OR allsegmentslist = 'b'
OR allsegmentslist like '%, b%'
OR allsegmentslist like '%, b,%'
Upvotes: 1
Reputation: 13248
You can just use the LIKE operator:
select *
from tablename
where allsegmentslist like '%, b,%'
or allsegmentslist like 'b,%'
or allsegmentslist like '%, b'
or allsegmentslist = 'b'
Upvotes: 0