有人可以帮我翻译带日期的CASE声明吗?

时间:2016-06-29 21:10:45

标签: sql tsql ssms

我需要修改存储过程,我无法理解如何在WHERE子句中操纵这些日期。特别是当END = 1时。我以前从未见过。

 CASE WHEN @DateFrom IS NULL THEN 1 ELSE
                        CASE WHEN INV.InvoiceDate > INV.EffectiveDate THEN 
                            CASE WHEN dateDiff(d, @DateFrom, INV.InvoiceDate) >= 0 
                                AND dateDiff(d, @DateTo, INV.InvoiceDate) <= 0 Then 1 else 0 end
                        ELSE
                            CASE WHEN dateDiff(d, @DateFrom, INV.EffectiveDate) >= 0 
                                AND dateDiff(d, @DateTo, INV.EffectiveDate) <= 0 Then 1 else 0 end
                        END 
                        END = 1

2 个答案:

答案 0 :(得分:0)

当您将其转换为单个案例时,似乎更容易理解:

CASE 
        WHEN @DateFrom IS NULL THEN 1
        WHEN @DateFrom IS NOT NULL  AND dateDiff(d, @DateFrom, INV.InvoiceDate) >= 0 AND dateDiff(d, @DateTo, INV.InvoiceDate) <= 0 THEN 1
        ELSE 0 END =1

你也可以试试这个

CASE 
    WHEN @DateFrom IS NULL  THEN 1 ELSE 
                        (CASE 
                        WHEN dateDiff(d, @DateFrom, INV.InvoiceDate) >= 0 AND dateDiff(d, @DateTo, INV.InvoiceDate) <= 0 THEN 1 ELSE 0
                        END)
            END)
            END = 1

我所得到的是这个案例的第二个层次是奇怪的。 whenelse个案例相同,因此不需要在那里。

(CASE 
        WHEN INV.InvoiceDate > INV.EffectiveDate
        THEN (CASE 
                    WHEN dateDiff(d, @DateFrom, INV.InvoiceDate) >= 0 AND dateDiff(d, @DateTo, INV.InvoiceDate) <= 0 THEN 1 ELSE 0
                    END)
        ELSE (CASE 
                WHEN dateDiff(d, @DateFrom, INV.EffectiveDate) >= 0 AND dateDiff(d, @DateTo, INV.EffectiveDate) <= 0 THEN 1 ELSE 0
                END)

答案 1 :(得分:0)

这个是错误的。我认为在某处缺少括号

 CASE 
        WHEN @DateFrom IS NULL  THEN 1 ELSE 
                            (CASE 
                            WHEN dateDiff(d, @DateFrom, INV.InvoiceDate) >= 0 AND dateDiff(d, @DateTo, INV.InvoiceDate) <= 0 THEN 1 ELSE 0
                            END)
                END)
                END = 1

enter image description here