TSQL如何在Where子句中使用if else

时间:2014-11-19 21:53:34

标签: sql sql-server

我想创建一个报告,该报告将有供用户选择的参数

-IsApprovedDate
-IsCatcheDate

我想知道如何在where子句中使用if else

示例如果用户选择IsApprovedDate,报表将根据批准的日期查找,否则将根据捕获日期进行查找。在我的查询中,我将根据奖励订单重量获得top10鱼尺寸,这是我的查询。

  ;WITH CTE AS
    (
        select  Rank() OVER (PARTITION BY c.trophyCatchCertificateTypeId order by c.catchWeight desc ) as rnk     
                ,c.id,c.customerId, Cust.firstName + ' '+Cust.lastName as CustomerName 
                ,CAST(CONVERT(varchar(10),catchWeightPoundsComponent)+'.'+CONVERT(varchar(10),catchWeightOuncesComponent) as  numeric(6,2) ) WLBS
                ,c.catchGirth,c.catchLength,ct.description county          
               ,t.description award--
               ,c.trophyCatchCertificateTypeId  
               ,s.specificSpecies--
               ,c.speciesId   

         from Catches c             
         INNER JOIN TrophyCatchCertificateTypes t on c.trophyCatchCertificateTypeId = t.id
         INNER JOIN Species s on c.speciesId = s.id
         INNER JOIN Counties ct on c.countyId = ct.id
         INNER JOIN Customers Cust on c.customerId = cust.id
         Where c.bigCatchCertificateTypeId is not null   
               and  c.catchStatusId =1 
         and c.speciesId =1 and c.isTrophyCatch =1 
         and c.catchDate >= @startDay and c.catchDate<=@endDay

     )
    Select * from CTE c1
     Where rnk <=10 

2 个答案:

答案 0 :(得分:1)

只需使用条件逻辑:

where . . . and
      ((@IsApprovedDate = 1 and c.ApprovedDate >= @startDay and c.ApprovedDate <= @endDay) or
       (@IsCatchDate = 1 and c.catchDate >= @startDay and c.catchDate <= @endDay)
      )

编辑:

我实际上会把它写成:

where . . . and
      ((@IsApprovedDate = 1 and c.ApprovedDate >= @startDay and c.ApprovedDate < dateadd(day, 1 @endDay) or
       (@IsCatchDate = 1 and c.catchDate >= @startDay and c.catchDate < dateadd(day, 1, @endDay))
      )

这是一个更安全的构造,因为它在日期值有时和有时没有时起作用。

答案 1 :(得分:1)

如果在代码中动态构建WHERE子句然后执行它,性能会好得多。