Tworzenie funkcji sprawdza, czy rok jest rokiem przestępnym
Ta prosta funkcja sprawdza jeden rok i zwraca wartość true lub false zależnie od roku za pomocą jednego wiersza kodu
This simple little function is normally called by other database operation calculating age and year differences.
When you run DATEPART DAYOFYEAR and compare the number of days on 3rd March then a leap year will return one more day, which is correct, but needs to be coded around for calculating someones age.
To get around this, we append this function to one of the dates to subtract one day after February 29.
CREATE FUNCTION Dates.GetLeapYear(@Date DATETIME2) RETURNS BIT AS BEGINDECLARE @Ret BIT=(CASE WHEN DATEPART(YEAR,@Date)%4<>0 OR (DATEPART(YEAR,@Date)%100=0 AND DATEPART(YEAR,@Date)%400<>0) THEN 0 ELSE 1 END)RETURN @RetENDGO
SELECT [dbo].[GetLeapYear]('01-01-1900') [1900],[dbo].[GetLeapYear]('01-01-1901') [1901],[dbo].[GetLeapYear]('01-01-1902') [1902],[dbo].[GetLeapYear]('01-01-1903') [1903],[dbo].[GetLeapYear]('01-01-1904') [1904]
Only 1904 will return true as expected.