我可以在WHERE子句中使用CASE语句吗?

时间:2016-12-22 09:19:45

标签: sql

EDITED

我想检查一个条件,如果另一个条件为真,否则

 DECLARE @id INT= 1;

 SELECT * 
   FROM TABLE1
  WHERE ETID = CASE  
          WHEN ID = @id THEN 
            1 
          ELSE 
            @id = 0 
        END

2 个答案:

答案 0 :(得分:0)

可能,但很可能不需要。

DECLARE @id INT= 1;

 SELECT * 
   FROM TABLE1
  WHERE ETID = 
        CASE  
          WHEN ID = @id THEN 1 
          WHEN @id = 0  THEN ...
          WHEN ...
          ELSE ...
        END

替代解决方案

DECLARE @id INT= 1;

 SELECT * 
   FROM TABLE1
  WHERE    (ID = @id and ETID = 1)
        or (@id = 0 ...)
        or ...

答案 1 :(得分:0)

逆向工程:

  

我想检查一个条件,如果另一个条件为真,否则

    WHERE ETID = CASE  
            WHEN ID = @id THEN 
              1 
            ELSE 
             @id = 0 
          END

让我们重建实际情况(至少尝试这样做):

  if (ID = @id) then 
    if (ETID = 1) then 
      obtain record
  else if (ID != @id) -- "else" in case
    obtain record -- want to check one condition...else NOT

然后让我们写下:

 select *
   from Table1
  where (ID = @id) and (ETID = 1) or -- check one condition if another condition true...
        (ID <> @id)                  -- ...else not

但是,由于问题非常含糊,其他一些变体是可能的,例如:

 select *
   from Table1
  where (ID = @id) and (ETID = 1) or -- check one condition if another condition true...
        (ETID <> 1)                  -- ...else not

根据一个条件另一个条件意味着