Reputation: 5038
I read the docs and some questions like this and this. Still I have some issues to get my query to work.
In my table I have a varchar
field that contains values separated by comma. Examples of real values are:
Note: the spaces can be present or not.
My query must find all the records that have, say, T1
in this field but not T11
. IN the case above all the first 4 rows should be returned.
I know that the pattern for the LIKE
operator is defined using the placeholder %
, _
, []
and [^]
.
But:
%T1%
finds also T11
, T12
, etc...%T1
works only if T1
is the last itemT1
works only if T1
is the only itemT1%
works only if T1
is the first itemSo I ended up with this query:
field LIKE '%T1' OR field LIKE 'T1,%' OR field LIKE '%,T1,%`
The first clause finds T1
if it's the only item or the last item.
The second clause finds T1
if it's the first item.
The last clause finds T1
if it's in the middle of other items.
But it does not work if there are spaces (i.e. T1 , T2
).
I should add all the other cases... It seems a bit ugly to me. Is there a more elegant way to achieve the same goal?
Upvotes: 0
Views: 539
Reputation: 60
This should work without replace
select * from
(values ('T1'),
('T1, T3, T11, T12'),
('T18, T1'),
('T18, T11'),
('T2, T3'))
as X(field )
where field like '%T1[^0-9]%'
or field like '%T1'
Upvotes: 0
Reputation: 69769
If you replace all the spaces, then add a leading and a trailing delimiter to your column, e.g.
CONCAT(',', REPLACE(field, ' ', ''), ',')
converts T1, T3, T11, T12
into ,T1,T3,T11,T12,
You can then search for just ,T1,
since you've taken care of the start and end cases by adding the extra delimiters, e.g.
WHERE CONCAT(',', REPLACE(field, ' ', ''), ',') LIKE '%,T1,%';
Or, if you are using a version of SQL Server that supports it, you could use:
WHERE EXISTS
( SELECT 1
FROM STRING_SPLIT(Field, ',') AS ss
WHERE TRIM(ss.value) = 'T1'
);
I wouldn't expect this to outperform LIKE
though
Upvotes: 2
Reputation: 112382
You can remove the spaces and add a comma at the beginning and at the end.
WHERE
(',' + REPLACE(field, ' ', '') + ',') LIKE '%,T1,%`
Upvotes: 1
Reputation: 50044
You can replace out space characters to help clean this up:
WHERE
(
REPLACE(field, ' ', '') LIKE '%,T1'
OR REPLACE(field, ' ', '') LIKE 'T1,%'
OR REPLACE(field, ' ', '') LIKE '%,T1,%'
)
Upvotes: 0