Saturday, 14 February 2015

SQL SERVER – Script to Find Leap Year

A leap year has 366 days. A leap year has 29 days for February month. Suppose you want to find if year is Leap year or not, you can use many methods. But this is one of the simplest methods. In our example I have passed the year 2000 as a variable to @year but you can change it to any year which you want to check for leap year.
DECLARE @YEAR SMALLINTSET @YEAR=2000SELECT @YEAR AS YEAR,CASE
DAY
(EOMONTH(DATEADD(DAY,31,DATEADD(YEAR,@YEAR-1900,0))))WHEN 29 THEN 'YES' ELSE 'NO'END AS LEAP_YEAR
GO
The result is
YEAR LEAP_YEAR
 ------ ---------
 2000 YES
The logic is from the given year create a Date which results for Feb 01 of that year. You can do this by adding 31 (DATEADD(YEAR,@YEAR-1900,0) results for Jan 01 of that year). Using EOMONTH finds the last day of the month. Using DAY function find out day value. If it is 29, it is a leap year otherwise it is non Leap year.

No comments:

Post a Comment