Comment trouverez-vous le dimanche dernier d'un mois à SQL 2000? P>
10 Réponses :
Vache sacrée, c'est laid, mais voici:
SELECT DATEADD(day,DATEDIFF(day,'19000107',DATEADD(month,DATEDIFF(MONTH,0,GETDATE() /*YourValuehere*/),30))/7*7,'19000107') Edit: A correct, final, working answer from my colleague.
Quelqu'un peut-il s'il vous plaît expliquer comment cela fonctionne? Plus précisément, pourquoi '19000107' et '30' sont utilisés dans les fonctions DaadDD et DaturaIff, respectivement? Merci.
@Sikander: 19000107 code> est utilisé car
7 janvier, 1900 code> est un dimanche arbitraire dans le passé lointain.
DECLARE @LastDateOfMonth smalldatetime SELECT @LastDateOfMonth = DATEADD(month, DATEDIFF(month, -1, GETDATE()), 0) -1 Select DATEADD(dd,-( CASE WHEN DATEPART(weekday,@LastDateOfMonth) = 1 THEN 0 ELSE DATEPART(weekday,@LastDateOfMonth) - 1 END ),@LastDateOfMonth)
Une approche alternative, empruntée à la pratique de l'entreposage de données. Créez une table de dimension de date et pré-chargez-la pendant 10 ans, ou ainsi.
SELECT max(FullDate) FROM dimDate WHERE DayOfWeek = 'Sunday' AND Month = 11 AND Year = 2009;
select next_day(last_day(sysdate)-7, 'Sunday') from dual
select dateadd(day,1-datepart(dw, getdate()), getdate())
Cela ne renvoie que le dimanche précédent et non le dernier dimanche du mois.
dimanche prochain en SQL, quel que soit le premier jour de la semaine: Retours 2011-01-02 23: 59: 59.000 Le 22 décembre 2010:
select DateADD(ss, -1, DATEADD(week, DATEDIFF(week, 0, getdate()), 14))
Je trouve difficile à comprendre certaines de ces solutions, voici ma version avec des variables pour expliquer les étapes.
ALTER FUNCTION dbo.fn_LastSundayInMonth ( @StartDate DATETIME ,@RequiredDayOfWeek INT /* 1= Sunday */ ) RETURNS DATETIME AS /* A detailed step by step way to get the answer... SELECT dbo.fn_LastSundayInMonth(getdate()-31,1) SELECT dbo.fn_LastSundayInMonth(getdate()-31,2) SELECT dbo.fn_LastSundayInMonth(getdate()-31,3) SELECT dbo.fn_LastSundayInMonth(getdate()-31,4) SELECT dbo.fn_LastSundayInMonth(getdate()-31,5) SELECT dbo.fn_LastSundayInMonth(getdate()-31,6) SELECT dbo.fn_LastSundayInMonth(getdate()-31,7) */ BEGIN DECLARE @MonthsSince1900 INTEGER DECLARE @NextMonth INTEGER DECLARE @DaysToSubtract INTEGER DECLARE @FirstDayOfNextMonth DATETIME DECLARE @LastDayOfMonthDayOfWeek INTEGER DECLARE @LastDayOfMonth DATETIME DECLARE @ReturnValue DATETIME SET @MonthsSince1900=DateDiff(month, 0, @StartDate) SET @NextMonth=@MonthsSince1900+1 SET @FirstDayOfNextMonth = DateAdd(month,@NextMonth, 0) SET @LastDayOfMonth = DateAdd(day, -1, @FirstDayOfNextMonth) SET @ReturnValue = @LastDayOfMonth WHILE DATEPART(dw, @ReturnValue) <> @RequiredDayOfWeek BEGIN SET @ReturnValue = DATEADD(DAY,-1, @ReturnValue) END RETURN @ReturnValue END
Voici la bonne façon, comptant @@ datefirst