Connect with MSSQLTips
Got a SQL tip?
We want to know!
SQL Server Function to Determine a Leap Year
By: Armando Prato | Read Comments (28) | Related Tips: More > Dates |
SolutionYes, there a few rules to consider when determining when a year is a leap year. For instance, contrary to popular belief not all years divisible by 4 are leap years. For instance, the year 1900 was not a leap year. However, you needn't bother yourself about leap year rules... you can let the SQL Server engine do the work for you!
The following scalar function takes in a year and returns a bit flag indicating whether the passed in year is a leap year or not.
create function dbo.fn_IsLeapYear (@year int) returns bit as begin return(select case datepart(mm, dateadd(dd, 1, cast((cast(@year as varchar(4)) + '0228') as datetime))) when 2 then 1 else 0 end) end go |
Here are a few examples:
select dbo.fn_IsLeapYear(1900) as 'IsLeapYear?' select dbo.fn_IsLeapYear(2000) as 'IsLeapYear?' select dbo.fn_IsLeapYear(2007) as 'IsLeapYear?' select dbo.fn_IsLeapYear(2008) as 'IsLeapYear?' |
Next Steps
- Read more about the DATEPART function and its parameters in the SQL Server Books Online
- Read more about the DATEADD function and its parameters in the SQL Server Books Online
- Read more about the User Defined Function types in the 2000 and 2005 Books Online
- Check out these related tips:
- Daylight Savings Time Functions in SQL Server
- Date/Time Conversions Using SQL Server
- Handling Weeks that Overlap Years in a Date Dimension in a SQL Server Data Warehouse
- Converting Invalid Date Formats Using SQL Server 2000 Data Transformation Services
- Transforming Invalid Data Formats in SQL Server 2000 DTS Using ActiveX Script
Last Update: 6/25/2008
source : http://www.mssqltips.com/sqlservertip/1527/sql-server-function-to-determine-a-leap-year/
No comments:
Post a Comment