Home Forums SQL Server 7,2000 T-SQL how i can find total no. of days in month in SQL Server2000? RE: how i can find total no. of days in month in SQL Server2000?

  • Well, everything depends on what data you have and what is the desired result... SQLS doesn't have any table that would directly store numbers of days in all months, and also it doesn't offer any function that would directly calculate it. You can create your own UDF, if you'll be needing it often.

    There is a DATEDIFF function that will tell you how many days it is from one date to another - so if you feed it with the first and last date of a month, you'll get the number of days in that month. Following SQL is what I'm using for similar purposes (credits should go to Kenneth Wilhelmsson)

    -- date of the 1st of month

    select convert(char(6), @date, 112) + '01'

    -- date of the last day of month

    select dateadd(day, -1, dateadd(month, 1, convert(char(6), @date, 112) + '01'))

    Well, now try to stuff this into the DATEDIFF and you should get a number of days in the month.

    SELECT DATEDIFF(day, convert(char(6), @date, 112) + '01', DATEADD(day, -1, DATEADD(month, 1, convert(char(6), @date, 112) + '01'))) + 1

    HTH, Vladan

    EDIT: Sorry for not declaring the variable. You'll need to declare it and assign a value to i - like this

    declare @date datetime

    set @date = '2005.04.01'