Tuesday, 30 June 2015

How to Determine a Leap Year or not in SQL Server by using User Defined Function (UDF)?


A leap year is a year containing one additional day and lasts 366 days instead of the usual 365.
Rule to determine if a year is a leap year:
– leap year is any year that is divisible by 400 (2000, 2400 are leap years…) or by 4 (2004, 2008 are leap years…) but it must not be divisible by 100 (2100, 2200 are NOT leap years…)

We will create a User Defined Function (UDF) that accepts a DATETIME value and checks if a year is a leap year:

CREATE FUNCTION [dbo].[Udf_Rajendra_LeapYearCheck] (@MyDate DATETIME)
RETURNS varchar(50)
AS
BEGIN
DECLARE @ReturnString varchar(50)
SET @ReturnString = CASE WHEN (YEAR(@MyDate) % 4 = 0 AND YEAR(@MyDate) % 100 != 0)
OR YEAR(@MyDate) % 400 = 0
THEN 'The year is a leap year'
ELSE 'The year is NOT a leap year'
END
RETURN @ReturnString
END
GO

To use this user-defined function:
SELECT dbo.[Udf_Rajendra_LeapYearCheck] ('2015-06-30')

No comments:

Post a Comment