2009-07-09 8 views
10

Io uso DATEDIFF funzione per filtrare i record aggiunti solo questa settimana:È possibile impostare l'inizio della settimana per la funzione DATEDIFF di T-SQL?

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

e ho notato quello che si presume ciò settimana inizia Domenica. Ma nel mio caso preferirei impostare l'inizio della settimana il lunedì. È possibile in qualche modo in T-SQL?

Grazie!


Aggiornamento:

Di seguito è riportato un esempio che mostra ciò che DATEDIFF non controlla @@DATEFIRST variabile quindi ho bisogno di un'altra soluzione.

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 

uscita:

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) 

26 lug 2009 è di Domenica, e voglio DATEDIFF restituisce 0 in terza colonna anche.

+0

Ci scusiamo per non aver controllato che DateFirst sia stato controllato da datediff, che avrebbe indovinato, ho aggiornato la mia risposta per tenerne conto. – Tetraneutron

risposta

19

Sì è possibile

SET DATEFIRST 1; -- Monday 

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

Sembra datediff non rispetta la DATEFIRST, in modo da fargli fare funzionare così come questo

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 

rubato da

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

+1

SQL Server non considera il valore di variabile ** DATEFIRST **, da msdn docs: _Specifying SET DATEFIRST non ha alcun effetto su DATEDIFF. DATEDIFF utilizza sempre domenica come primo giorno della settimana per garantire che la funzione sia deterministica._ Soluzione piacevole! :) – Rynkadink

Problemi correlati