我在构建where子句的时候 对其中一个字段允许有多个值 该怎么写这个句子呢?
具体情况是 a 的可用值是1,2,3,4 用户可以选择多个值
比如用户选了 1,3,4
我现在的where子句要检索出a=1或者a=3或者a=4且a!=2的所有结果
注意where子句除了条件a 还有其他条件b,c,d....
这个句子应该怎么写好?

解决方案 »

  1.   


    declare @str varchar(20)
    set @str='1,2,3,4'
    select * from tbl where charindex(','+ltrim(a),','+@str)>0
      

  2.   

    where a in(1,2,3,4) and b='anything' and c=……
      

  3.   

    你的1,3,4如果是一个串(例如@s)可如下:
    where charindex(','+cast(a as varchar)+',' , ','+@s+',') > 0 and 其他条件

    where ','+@s+',' LIKE '%,'+cast(a as varchar)+',%'  and 其他条件
      

  4.   

    用in来实现嘛,相当于是要查的变量的集合     where   ??  in(1,2,3)
      

  5.   

    where a in( select a=1 union select 2 union select 3)
    and a not in( select a=4 union select 5 union select 6)
    and b....
    and c....