Home Forums SQL Server 2008 SQL Server 2008 - General Trying to set variable to last day of current month, but seeing NULL instead of 28, 30 or 31? RE: Trying to set variable to last day of current month, but seeing NULL instead of 28, 30 or 31?

  • You can use this function

    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

    SELECT dbo.fnGetMonthDays(CONVERT(DATE,'2014-02-01'))

    --28

    SELECT dbo.fnGetMonthDays(CONVERT(DATE,'2016-02-01'))

    --29

    Igor Micev,My blog: www.igormicev.com