Get month days

,

SELECT dbo.fnGetMonthDays(CONVERT(DATE,'2014-02-01'))
--28
SELECT dbo.fnGetMonthDays(CONVERT(DATE,'2016-02-01'))
--29
--Gets number of days for a month. Leap years taken in consideration.
CREATE FUNCTION dbo.fnGetMonthDays(@myDate DATE) RETURNS INT
AS
BEGIN	
	DECLARE @isLeap INT = 0
	IF (YEAR(@myDate) % 400 = 0 OR (YEAR(@myDate) % 4 = 0 AND YEAR(@myDate) % 100 !=0))
		SET @isLeap=1
	DECLARE @month INT = MONTH(@myDate)
	DECLARE @days INT
	SELECT @days =
		CASE
			WHEN @month=1 THEN 31
			WHEN @month=2 THEN 28 + @isLeap
			WHEN @month=3 THEN 31
			WHEN @month=4 THEN 30
			WHEN @month=5 THEN 31
			WHEN @month=6 THEN 30
			WHEN @month=7 THEN 31
			WHEN @month=8 THEN 31
			WHEN @month=9 THEN 30
			WHEN @month=10 THEN 31
			WHEN @month=11 THEN 30
			WHEN @month=12 THEN 31
		END 
		RETURN @days
END

Rate

4 (5)

Share

Share

Rate

4 (5)