Reputation: 51
I have a TEXT column in my Table T and contains some values separated by Commas.
Example
Columns BNFT has text values such as
B20,B30,B3,B13,B31,B14,B25,B29,B1,B2,B4,B5
OR
B1,B2,B34,B31,B8,B4,B5,B33,B30,B20,B3
I want to return result in my query only if B3 is present. It should not consider B30-B39 or B[1-9]3 (i.e. B13, B23 .... B93).
I tried with below query, but want to implement REGEXP or REGEXP_LIKE/INSTR etc. Haven't used them before and unable to understand also.
Select *
FROM T
Where BNFT LIKE '%B3,%' or BNFT LIKE '%B3'
Pls advise
Procedures will not work. Query must start with Select as 1st statement.
Upvotes: 0
Views: 4906
Reputation: 81
This can be easily achieve by CTE, REGEXP/REGEXP_Like/INSTR works better with oracle, for MS SQL Server you can try this
DECLARE @CSV VARCHAR(100) ='B2,B34,B31,B8,B4,B5,B33,B30,B20,B3'; SET @CSV = @CSV+',';
WITH CTE AS ( SELECT SUBSTRING(@CSV,1,CHARINDEX(',',@CSV,1)-1) AS VAL, SUBSTRING(@CSV,CHARINDEX(',',@CSV,1)+1,LEN(@CSV)) AS REM UNION ALL SELECT SUBSTRING(A.REM,1,CHARINDEX(',',A.REM,1)-1)AS VAL, SUBSTRING(A.REM,CHARINDEX(',',A.REM,1)+1,LEN(A.REM)) FROM CTE A WHERE LEN(A.REM)>=1 ) SELECT VAL FROM CTE WHERE VAL='B3'
Upvotes: 0
Reputation: 1271131
The first advice is to fix your data structure. Storing lists of ids in strings is a bad idea:
That said, sometimes we are stuck with other people's bad design decisions.
In SQL Server, you would do:
where ',' + BNFT + ',' LIKE '%,33,%'
This question was originally tagged MySQL, which offers find_in_set()
for this purpose:
Where find_in_set(33, BNFT) > 0
Upvotes: 3
Reputation: 44991
Select *
FROM T
Where ',' + BNFT + ',' LIKE '%,B3,%';
or
Select *
FROM T
Where CHARINDEX (',B3,',',' + BNFT + ',') > 0;
Upvotes: 0