2

我想执行这个查询

select * from locations where region=1 or region=2

但在某些情况下,我不想在 WHERE ( or region=2) 中包含第二个子句。有没有办法有条件地运行 or 语句?

4

5 回答 5

2

检查 where 语句中的条件

select * from locations 
where region=1 
or (region=2 and @checkRegion2=1)
于 2013-09-15T19:24:40.723 回答
2

如果您想要通用查询,您可以为此声明表变量(我假设您使用的是 SQL 服务器):

declare @regions table (id int primary key)

然后根据条件填写:

insert into @regions select 1
if @use2 = 1
    insert into @regions select 2

现在您可以运行此查询:

select *
from location as l
where exists (select * from @regions as r where r.id = l.region)

或者

select *
from location as l
where l.region in (select r.id from @regions as r)
于 2013-09-15T19:26:49.403 回答
0
DECLARE @RUNAFTERBIT VARCHAR(10)
SET @RUNAFTERBIT = 'TRUE'

IF @RUNAFTERBIT = 'TRUE'
  SELECT * FROM LOCATIONS WHERE REGION = 1 OR REGION = 2
ELSE
  SELECT * FROM LOCATIONS WHERE REGION = 1 
END IF
于 2013-09-15T19:02:22.937 回答
0

您可以使用动态 SQL:

DECLARE @Query VARCHAR(MAX) = 'SELECT * FROM locations WHERE region=1 '

IF(@RUNAFTERBIT = 'TRUE')
BEGIN
    SET @Query = @Query + ' OR REGION = 2'
END

EXEC(@Query)
于 2013-09-15T19:33:57.647 回答
0

CASE某些情况下,表达式可用于执行短路评估:

declare @AlternateRegion as Int = 2;

select *
  from Locations
  where case
    when Region = 1 then 1
    when @AlternateRegion is not NULL then
      case when Region = @AlternateRegion then 1 else 0 end
    else 0
    end = 1

CASE在存在聚合函数的情况下不能可靠地提供短路评估。请参阅CASE / COALESCE 并不总是按文本顺序进行评估, 并且聚合不遵循 CASE 的语义

于 2013-09-15T20:28:53.740 回答