如何检查存储在varchar列中的逗号分隔列表中是否包含数字?

问题描述 投票:8回答:6

我有一张桌子有varcharcategoryIds。它包含一些用逗号分隔的ID,例如:

id       categoryIds
-------------------- 
1        3,7,12,33,43

我想做一个select语句并检查该列中是否存在int。像这样的东西:

select * 
from myTable 
where 3 in (categoryIds)

我知道这可以通过this在MySQL中实现,但是它也可以在SQL Server中完成吗?

我已经尝试将int转换为char,它运行以下语句:

select * 
from myTable 
where '3' in (categoryIds)

但它似乎没有任何“开箱即用”支持逗号分隔列表,因为它什么都不返回。

sql sql-server
6个回答
12
投票

您应该重新设计此表以将这些值从逗号分隔为单独的行。但是,如果无法做到这一点,那么您将继续执行字符串比较:

DECLARE @id INT = 3
DECLARE @stringId VARCHAR(50) = CAST(@id AS VARCHAR(50))

SELECT * 
FROM MyTable 
WHERE categoryIds = @stringId -- When there is only 1 id in the table
OR categoryIds LIKE @stringId + ',%' -- When the id is the first one
OR categoryIds LIKE '%,' + @stringId + ',%' -- When the id is in the middle
OR categoryIds LIKE '%,' + @stringId -- When the id is at the end

3
投票
SELECT * 
FROM myTable 
WHERE (',' + RTRIM(categoryIds) + ',') LIKE '%,' + @stringId + ',%'

这里@stringId是你要搜索的文本。通过这种方式,您可以避免不必要的多个条件

亲切的问候,Raghu.M。


1
投票

不确定这是否比DavidG的建议更快或更慢,但为了只用一张支票获得相同的匹配,你可以这样做:

DECLARE @categoryId INT
SET @categoryId = 3

SELECT *
FROM myTable
WHERE CHARINDEX(',' + CAST(@categoryId AS VARCHAR(MAX)) + ',', ',' + categoryIds + ',') > 0

0
投票

您可以像这样使用动态SQL:

DECLARE     @categoryIds    nvarchar(50) = '1, 2, 3, 4, 5'

EXEC        ('SELECT      *
              FROM        myTable
              WHERE       categoryId IN (' + @categoryIds + ')')

0
投票

SELECT * FROM user_master WHERE(user_tags regexp'[[: :]]'或user_tags regexp'[[: :]]')


-4
投票

使用FIND_IN_SET() mysql函数

句法

SELECT * FROM <table name> as a WHERE FIND_IN_SET(value to search in string,comma separated string);

SELECT * FROM <table name> as a WHERE FIND_IN_SET(5,"1,2,3,4,5,6");
© www.soinside.com 2019 - 2024. All rights reserved.