lunes, 30 de diciembre de 2013

Leap Year function in Sql Server

Here is a function to determine if a year is a leap year in Sql Server.

The rules to determine a leap year are:

  • Must be divisible by 4.
  • Must NOT be divisible by 100.
  • Must be divisible by 400.
CREATE FUNCTION isLeapYear(
 @date DATETIME
) RETURNS BIT 
AS
BEGIN
 DECLARE 
  @year INT,
  @isLeapYear BIT
  
 SET @year = YEAR(@date)

 IF @year % 4 = 0 AND (@year % 100 <> 0 OR @year % 400 = 0)
 BEGIN
  SET @isLeapYear = 1
 END
 ELSE
 BEGIN
  SET @isLeapYear = 0
 END 

 RETURN @isLeapYear
END

No hay comentarios: