sql – 如何检查存储在varchar列中的逗号分隔列表中是否包含数字
发布时间:2020-12-12 06:34:13 所属栏目:MsSql教程 来源:网络整理
导读:我有一个varchar列categoryIds的表.它包含一些用逗号分隔的ID,例如: id categoryIds-------------------- 1 3,7,12,33,43 我想做一个select语句并检查该列中是否存在int.像这样的东西: select * from myTable where 3 in (categoryIds) 我知道这可以通过thi
我有一个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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |