Tsql在WHERE中使用CASE WHEN来检索单个时段或所有时段的数据

时间:2017-05-18 21:13:21

标签: sql-server visual-studio

我创建了一份报告,我需要显示一年中的一个时段或同一年的所有时段的金额。 检索一段时间没问题...

WHERE 
    (TransactionType = 12) 
    AND (FiscalYear = @FiscalYear)
    AND (AccountNumber = 'xxxx') 
    AND (FiscalPeriod = @FiscalPeriod)  

一年中所有时期都没有问题

WHERE 
    (TransactionType = 12) 
    AND (FiscalYear = @FiscalYear) 
    AND (AccountNumber = 'xxxx') 
    AND FiscalPeriod between 1 and 14

但是我想创建一个参数,用户可以在其中输入单个句点编号以查看该单个月/期间的数据,但如果他们将该参数留空(''或IS NULL)则为期间1的数据 - 14将被退回。

我试过了

WHERE 
    (TransactionType = xxx)  
    AND (FiscalYear IN (@FiscalYear)) 
    AND (AccountNumber IN (@AccountNumber)) 
    AND (FiscalPeriod = @FiscalPeriod) 
    OR (TransactionType = xxx)  
    AND (FiscalYear IN (@FiscalYear)) 
    AND (AccountNumber IN (@AccountNumber)) 
    AND (GLTR.FiscalPeriod between 1 and 14)

......上面给了我一切......因为OR

如果可以通过A CASE WHEN实现这一点,我没有正确的...... 试过......

WHERE 
    (gltr.TransactionType = 12) 
    AND (gltr.FiscalYear = 2015) 
    AND (coa.AccountNumber = '2000') 
    AND (gltr.FiscalPeriod = CASE WHEN @FiscalPeriod IS NULL THEN '' ELSE @FiscalPeriod END) 
    OR (gltr.FiscalYear = 2015) 
    AND (coa.AccountNumber = '2000') 
    AND (gltr.FiscalPeriod BETWEEN 1 AND 14)

然后试了......

WHERE 
    (gltr.TransactionType = 12) 
    AND (gltr.FiscalYear = 2015) 
    AND (coa.AccountNumber = '2000') 
    AND (gltr.FiscalPeriod = CASE WHEN NOT(@FiscalPeriod IS NULL) THEN @FiscalPeriod ELSE BETWEEN 1 and 14) 

......不要去

......以及上述两种变化......旋转我的车轮,并知道有办法实现这一目标。

由于

1 个答案:

答案 0 :(得分:2)

我认为这就是你想要的:

where TransactionType = xxx
  and FiscalYear = @FiscalYear
  and AccountNumber = @AccountNumber
  and (
        FiscalPeriod = @FiscalPeriod 
    or (@FiscalPeriod is null and FiscalPeriod between 1 and 14)
    )