SHEKHAR SHETE
SHEKHAR SHETE

Reputation: 6066

How to return row matching exact string from csv column in sql?

I have table column which holds CSV values. eg: 2,3,4,1,13 I want to find specific string from the CSV and return the row matching exact search string from csv.

Table:

tbl_A(ID,name,Csv)

ID name   CSV
1  ABC    1,2,13,15
2  PQR    1,4,3,5

@SearchSting=13

Output required:

ID name  CSV
1   ABC  1,2,13,15


select * from tbl_A  where csv like '%@SearchSting%' 

This will give both rows. :(

Help appreciated!

Upvotes: 0

Views: 568

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

Left me start by saying that this is a poor database design and should be avoided. If possible, you should normalize your database and change that Csv column to a table containing each value in it's own row. Further reading: Is storing a delimited list in a database column really that bad?

However, if normalizing your database is not an option, you can do this:

SELECT Id, Name, Csv
FROM tbl_A
WHERE ',' + Csv + ',' LIKE '%,' + @SearchString  + ',%'

Upvotes: 2

Related Questions