SQL:在WHERE中使用OR时的情况

时间:2016-12-14 09:22:21

标签: sql sql-server

假设存储过程获得3个参数,这些参数都是boolean(1或0): @includeMode1@includeMode2@includeMode3

我想进行查询:

SELECT *
FROM [dbo].[MyTable] as P
WHERE P.Mode = 1 (if @includeMode1 = 1) OR P.Mode = 2 (if @includeMode2 = 1) OR P.Mode = 3 (if @includeMode3 = 1)

我似乎无法找到正确的方法,也很乐意听到是否有更有效的方法(表现)来取代or

3 个答案:

答案 0 :(得分:2)

如果所有三个都可以是' 1',那么这个:

SELECT *
FROM [dbo].[MyTable] as P
WHERE (P.Mode = 1 and @includeMode1 = 1) 
  OR (P.Mode = 2 and @includeMode2 = 1) 
  OR (P.Mode = 3 and @includeMode3 = 1)

答案 1 :(得分:0)

user_id

答案 2 :(得分:0)

替换or的一种有效方法是使用dynamic sql

rextester:http://rextester.com/RFHEC49942

create procedure [mytable_get_byMode] (@IncludeMode1 bit, @IncludeMode2 bit, @IncludeMode3 bit) as
begin;
  if coalesce(nullif(@IncludeMode1,0),nullif(@IncludeMode2,0),nullif(@IncludeMode3,0))=convert(bit,1)
  begin;
  declare @sql nvarchar(4000)
  select @sql =N'select *
    from [dbo].[MyTable] as P
    where P.Mode in ('
  +stuff(case when @IncludeMode1 = 1 then ',1' else '' end
        +case when @IncludeMode2 = 1 then ',2' else '' end
        +case when @IncludeMode3 = 1 then ',3' else '' end
        ,1,1,'')
        +N');';
  select @sql;
  --exec sp_executesql @sql;
  end;
end;
go
exec mytable_get_byMode 1,1,1;
exec mytable_get_byMode 0,1,1;
exec mytable_get_byMode 1,0,1;
exec mytable_get_byMode 0,0,0;