使用T-SQL从逗号分隔的数组中选择精确的表记录

时间:2012-09-04 15:13:14

标签: sql tsql

这让我无法理解我的简单大脑。以逗号分隔的已排序产品数组将传递给如下过程:

set @array = 'productID_47, productID_4'

select productID, price from Products 
where @array like '%' + productID + '%'

返回两条记录。大。 但是如果我有:

set @array = 'productID_47'

select productID, price from Products 
where @array like '%' + productID + '%'

再次,返回两条记录,这不是我想要的。 遗憾的是,产品代码是固定的。

感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:2)

我假设@array中只有一个项目时没有逗号:

select productID, price 
from Products  
where @array = productID --only one item, can use index
    or @array like productID + ',%'  --array starts with item, can use index
    or @array like '%, ' + productID + ',%' --item is in the middle of @array, cannot use index
    or @array like '%, ' + productID --item is at the end of @array, cannot use index
    or @array like '%,' + productID