2016-01-13 80 views
-1

我可以添加六天到一個日期,並得到我的期望,但如果我添加七天到同一日期,我得到相同的日期。爲什麼不同日期的數學運算產生相同的值?

我的意思是這個;當用戶輸入「2015年12月27日」作爲@BegDate參數的值,這個聲明:

DECLARE 
@Week1End datetime = DATEADD(Day, 6, @BegDate), 
@Week2Begin datetime = DATEADD(Day, 7, @BegDate); 

...結果按@ Week1End和@ Week2Begin是相同的日期(2016 -01-02),你可以從返回的結果集看到:

enter image description here

這是TSQL:

CREATE PROCEDURE [dbo].[variancePriceByProductWithPriceChangePercentage] 
    @Unit varchar(25), 
    @BegDate datetime, 
    @EndDate datetime 
AS 

DECLARE 
@Week1End datetime = DATEADD(Day, 6, @BegDate), 
@Week2Begin datetime = DATEADD(Day, 7, @BegDate); 

Select Ind.Description, 
    @BegDate BegDate, 
    @Week1End Week1End, 
    @Week1End Week2Begin, 
    @EndDate EndDate, 
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.QtyShipped ELSE 0 END) 
Week1Usage, 
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.QtyShipped ELSE 0 END) 
Week2Usage, 
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END) 
Week1Price, 
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.Price ELSE 0 END) - 
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.QtyShipped ELSE 0 END) 
UsageVariance, 
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.QtyShipped ELSE 0 END) 
- 
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END) 
PriceVariance, 
    (SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.QtyShipped ELSE 0 
END) - 
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END)) 
    /
NULLIF(SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END),0) 
PercentageOfPriceVariance 
    From InvoiceDetail Ind 
    Where Ind.Unit = @Unit 
    AND Ind.InvoiceDate BETWEEN @BegDate AND @EndDate 
    Group By Ind.Description 

所以爲什麼@BegDate + 6等同於同樣的事情@BegDate + 7

回答

2
@Week1End Week1End, 
@Week1End Week2Begin, 

看看這塊再次代碼...

+0

嗯,就是這樣;我之前解決了這個問題,而另一個複製和粘貼作業將它帶回來。我現在使用LINQPad刪除並重新創建SP,因爲這比Server Explorer更容易。 –

1

你肯定:

DECLARE @BegDate datetime = GETDATE() 

SELECT @BegDate, DATEADD(Day, 6, @BegDate), DATEADD(Day, 7, @BegDate); 

結果:

enter image description here

我覺得你的問題在這裏:

@Week1End Week1End, 
@Week1End Week2Begin, ---<<<<<--- 

它應該是:

@Week1End Week1End, 
@Week2BeginWeek2Begin, ---<<<<<--- 
+0

我知道這似乎就沒有任何意義,但你可以看到我上面得到的結果:Week1End和Week2Begin返回相同的值。 –

+0

看到我的回答更新 –

相關問題