Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Is a specified year a leap year? (See related posts)

This function returns a 1 if the supplied year is a leap year, otherwise 0
   1  
   2  CREATE FUNCTION dbo.f_is_leap_year(@year INTEGER)
   3  RETURNS BIT AS 
   4  BEGIN
   5  
   6    IF @year % 400 = 0
   7       -- Years divisible by 400 (e.g. 1600, 2000) are always leap years
   8       RETURN 1 
   9    ELSE
  10    BEGIN
  11      IF @year % 100 = 0
  12         -- Years not divisible by 400 but divisible by 100 (e.g. 1900) are never leap years
  13         RETURN 0
  14      ELSE
  15      BEGIN
  16        IF @year % 4 = 0
  17           -- Years not divisible by 400 or 100 but divisible by 4 (e.g. 1976) are always leap years
  18           RETURN 1
  19        ELSE
  20           RETURN 0
  21      END
  22    END
  23  
  24    -- The following statement should never be reached (but the SQL syntax parser requires it)
  25    RETURN 0 
  26  
  27  END
  28  GO


   1  
   2  SELECT dbo.f_is_leap_year(2003) AS [2003], dbo.f_is_leap_year(2004) AS [2004], dbo.f_is_leap_year(2005) AS [2005]

You need to create an account or log in to post comments to this site.


Click here to browse all 5309 code snippets

Related Posts