I have a table with a varchar
column categoryIds
. It contains some IDs separated by commas, for example:
id categoryIds
--------------------
1 3,7,12,33,43
I want to do a select statement and check if an int exists in that column. Something like this:
select *
from myTable
where 3 in (categoryIds)
I know this is possible in MySQL by doing this , but can it be done in SQL Server as well?
I have tried casting the int to a char, which runs the following statement:
select *
from myTable
where '3' in (categoryIds)
But it doesn't look like there's any "out of the box" support for comma separated lists as it returns nothing.
7条答案
按热度按时间cgyqldqp1#
You should really redesign this table to split out those values from being comma separated to being in individual rows. However, if this is not possible, you are stuck with doing string comparison instead:
a2mppw5e2#
Here @stringId is your text to be searched. In this way you can avoid unnecessary multiple where conditions
Kind Regards, Raghu.M.
u0njafvf3#
Because it has not been mentioned yet, one might use STRING_SPLIT([values], ',') to achieve the desired check. The function is available since SQL Server 2016. Due the age of the question I assume that this perquisite wasn't met, the time it has been asked.
This should outperform the above mentioned string based comparisons.
mwkjh3gx4#
Not sure if this would be faster or slower than DavidG's suggestion, but in order to get the same matches with only one check, you can do:
elcex8rz5#
You could use dynamic SQL like this:
eeq64g8w6#
b1uwtaje7#
use
FIND_IN_SET()
mysql functionSyntax
Example