SQL WHERE CHARINDEX

时间:2012-07-29 22:32:34

标签: sql

我的专栏ServicetTypeIDs包含以下数据。我使用下面的where子句来搜索值,让我们说如果我的参数@ServiceTypes = 1,9它只会在两个1,9都存在时返回我的记录。我想返回包含1,9或记录的记录,其中包含1,9本身。我的where子句不正确。请帮忙

column
1
NULL
9
1
4,7
1,9

 WHERE
( @ServiceTypes is null or       
   charindex(','+SEP.ServiceTypeIDs+',',      
   ','+@ServiceTypes+',') > 0)))

1 个答案:

答案 0 :(得分:0)

如果你需要'1,9'选择('1','9','1,9')这里是一个短暂的条件

where (@ServiceTypes is null) or (','+@ServiceTypes+',' like '%,'+ServiceTypeIds+',%')

但对于'4,9',它只选择('9')。如果你想得到('4,7','1,9','9')这个面具就是条件

where (@ServiceTypes is null) 
      or 
      (','+ServiceTypeIds+',' like ',%'+SUBSTRING(@ServiceTypes,1,charindex(',',@ServiceTypes)-1)+',%')
      or
      (','+ServiceTypeIds+',' like ',%'+SUBSTRING(@ServiceTypes,charindex(',',@ServiceTypes)+1,1000)+',%')