我有一个带有varchar
列的表categoryIds
.它包含一些用逗号分隔的ID,例如:
id categoryIds
--------------------
1 3,7,12,33,43
Run Code Online (Sandbox Code Playgroud)
我想做一个select语句并检查该列中是否存在int.像这样的东西:
select *
from myTable
where 3 in (categoryIds)
Run Code Online (Sandbox Code Playgroud)
我知道这是可能在MySQL做这个,但它可以在SQL Server来完成呢?
我已经尝试将int转换为char,它运行以下语句:
select *
from myTable
where '3' in (categoryIds)
Run Code Online (Sandbox Code Playgroud)
但它似乎没有任何"开箱即用"支持逗号分隔列表,因为它什么都不返回.
Dav*_*idG 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
Run Code Online (Sandbox Code Playgroud)
SELECT *
FROM myTable
WHERE (',' + RTRIM(categoryIds) + ',') LIKE '%,' + @stringId + ',%'
Run Code Online (Sandbox Code Playgroud)
这里@stringId 是您要搜索的文本。通过这种方式,您可以避免不必要的多个 where 条件
亲切的问候, Raghu.M.
小智 7
由于尚未提及,因此可以使用STRING_SPLIT([values], ',')来实现所需的检查。该函数自 SQL Server 2016 起可用。由于问题的年龄,我认为在提出该问题时尚未满足此条件。
select [id], [categoryIds]
from [myTable]
where '3' in (select value from STRING_SPLIT([categoryIds], ','))
Run Code Online (Sandbox Code Playgroud)
这应该优于上述基于字符串的比较。
归档时间: |
|
查看次数: |
15644 次 |
最近记录: |