2009-07-09 59 views
10

我用DATEDIFF功能僅過濾上星期增加記錄:是否可以設置T-SQL DATEDIFF函數的星期開始?

DATEDIFF(week, DateCreated, GETDATE()) = 0 

,我注意到什麼它假設上週日開始一週什麼。但就我而言,我寧願在週一設置星期的開始。 T-SQL有可能以某種方式嗎?

謝謝!


更新:

下面是顯示什麼DATEDIFF不檢查@@DATEFIRST變量,所以我需要另一種解決方案的例子。

SET DATEFIRST 1; 

SELECT 
    DateCreated, 
    DATEDIFF(week, DateCreated, CAST('20090725' AS DATETIME)) AS D25, 
    DATEDIFF(week, DateCreated, CAST('20090726' AS DATETIME)) AS D26 
FROM 
(
    SELECT CAST('20090724' AS DATETIME) AS DateCreated 
    UNION 
    SELECT CAST('20090725' AS DATETIME) AS DateCreated 
) AS T 

輸出:

DateCreated    D25   D26 
----------------------- ----------- ----------- 
2009-07-24 00:00:00.000 0   1 
2009-07-25 00:00:00.000 0   1 

(2 row(s) affected) 

2009年7月26日是星期天,我想在DATEDIFF第三列返回0了。

+0

對不起,沒有檢查DateFirst是由datediff檢查,誰會猜到,我已經更新了我的答案,以考慮到這一點。 – Tetraneutron 2009-07-09 06:03:12

回答

19

是的,它可能

SET DATEFIRST 1; -- Monday 

http://msdn.microsoft.com/en-us/library/ms181598.aspx

看來DATEDIFF不尊重DATEFIRST,所以讓它這樣做這樣

create table #testDates (id int identity(1,1), dateAdded datetime) 
insert into #testDates values ('2009-07-09 15:41:39.510') -- thu 
insert into #testDates values ('2009-07-06 15:41:39.510') -- mon 
insert into #testDates values ('2009-07-05 15:41:39.510') -- sun 
insert into #testDates values ('2009-07-04 15:41:39.510') -- sat 

SET DATEFIRST 7 -- Sunday (Default 
select * from #testdates where datediff(ww, DATEADD(dd,[email protected]@datefirst,dateadded), DATEADD(dd,[email protected]@datefirst,getdate())) = 0 
SET DATEFIRST 1 -- Monday 
select * from #testdates where datediff(ww, DATEADD(dd,[email protected]@datefirst,dateadded), DATEADD(dd,[email protected]@datefirst,getdate())) = 0 

被盜從

運行

http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/8cc3493a-7ae5-4759-ab2a-e7683165320b

+1

確實,SQL Server不考慮** DATEFIRST **變量值,來自msdn文檔: _指定SET DATEFIRST對DATEDIFF沒有影響。 DATEDIFF總是使用星期日作爲一週的第一天,以確保功能是確定性的._ 很好的解決方法! :) – Rynkadink 2013-10-25 10:23:35

相關問題