如何在SQL Server中使用(IN)运算符

时间:2016-12-08 06:05:04

标签: sql sql-server sql-server-2008-r2

如何在SQL Server中使用IN运算符?我正在使用一个包含5列的表。但我想通过像

这样的存储过程获取选定的列
 Select * 
 From products 
 Where proprice between @price1 and @price2 
   and categoryid in (@cID)

执行此存储过程时,它会成功执行。但我将值传递给三个参数,我无法获得正确的数据返回。

数据样本:

ProductID ProductName ProductImage           ProductPrice
 20       Nike Shoe   ~/Images/NikeShoe1.jpg 5000

2 个答案:

答案 0 :(得分:0)

如果值以逗号分隔,请尝试此操作。另请阅读有关规范化的内容

Select * from products 
 where proprice between @price1 and @price2 and '%,'+categoryid+',%' like '%,'+@cID+'%,'

答案 1 :(得分:0)

试试这个:

确保您将参数传递为'1,2'而不是'(1,2)'

Select * 
from products 
where (proprice between @price1 and @price2) and (CHARINDEX(','+CAST(categoryid as VARCHAR(8000))+ ',', ','+@cID+',')>0)

如果您将参数传递为'(1,2)'

select @cid=REPLACE(@cid,'(','');
select @cid=REPLACE(@cid,')','');

Select * 
from products 
where (proprice between @price1 and @price2) and (CHARINDEX(','+CAST(categoryid AS VARCHAR(8000))+ ',', ','+@cID+',')>0)