SQL如何使用嵌套的AND过滤where语句

时间:2015-09-02 21:10:12

标签: sql sql-server

我有以下SQL查询:

SELECT eventuid
FROM date_contracts dc
WHERE 

        AND (@caseuid = @emptyuid OR dc.caseuid=@caseuid)


        -- date filters

        AND 
        ( 

         (
          @datetype = 0 AND 
          (datestart >= @startdate and dateend <= @enddate)
         )    
         OR 
         (
          @datetype = 1 AND 
          (dc.invoicedate BETWEEN @startdate AND @enddate)
         )
         OR
         (
          @datetype = 2 AND
          (dc.recorddate BETWEEN @startdate AND @enddate)
         )  
        )

我只在@caseuid = @emptyuid时执行“日期过滤器”。

  

有任何线索吗?

2 个答案:

答案 0 :(得分:0)

所以你想在@caseuid = @emptyuid

时过滤
  • 然后首先OR true
  • 现在内部条件将具有(False或Condition),因此只有在condition = true过滤器处于活动状态时,该行才会返回。
  • 但如果是@caseuid <> @emptyuid
  • 内部条件将是(真或条件)意味着总是true并且不会过滤任何行。
    • 同样希望dc.caseuid=@caseuid无论发生什么都不重要。

 SELECT *
 FROM TABLE
 WHERE 
     (@caseuid = @emptyuid OR dc.caseuid=@caseuid)
 AND 
     (  
       @caseuid <> @emptyuid OR
       (
         @datetype = 0 AND 
         (datestart >= @startdate and dateend <= @enddate)
       ) 
     )

ADD NOTE

那些查询不相等

如果我们有一个参数@datetype = 0和一行

  • (datestart >= @startdate and dateend <= @enddate) = false(首先OR
  • (dc.invoicedate BETWEEN @startdate AND @enddate) = true(第二OR

在操作版中:第一个OR为false,因为没有匹配dates,第二个和第三个OR也是false,因为不匹配datatype所以3 OR返回false。

但是在缩减版本中:

  • AND @datetype IN (0, 1, 2)返回true
  • AND (range1 or range2 or range3) range2为真所以3 OR都返回true

答案 1 :(得分:0)

我相信您可以简化您的查询,如下所示

SELECT eventuid
FROM date_contracts dc
WHERE (@caseuid = @emptyuid OR dc.caseuid=@caseuid)
AND @datetype IN (0, 1, 2)
AND ((datestart >= @startdate and dateend <= @enddate)
OR (dc.invoicedate BETWEEN @startdate AND @enddate)
OR (dc.recorddate BETWEEN @startdate AND @enddate));