RealWorldDevelopers
9/19/2016 - 11:33 PM

Is a Year a Leap Year SQL Function

Is a Year a Leap Year SQL Function

/*  
 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    SMALLINT  
 SET   @   YEAR   =   2000  
 SELECT   @   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.  
 */