我有一个varchar列categoryIds的表.它包含一些用逗号分隔的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)
但它似乎没有任何“开箱即用”支持逗号分隔列表,因为它什么都不返回.
解决方法
您应该重新设计此表以将这些值从逗号分隔为单独行.但是,如果无法做到这一点,那么您将继续进行字符串比较:
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