创建功能检查年份是否为leap年
这个简单的函数使用一行代码检查传入的年份,并根据年份返回true或false
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.