Search code examples
sqlsql-serversql-server-2005t-sqldatetime

SQL Server 2005 Get First and Last date for any Month in any Year


I have a stored procedure that has to accept a month as int (1-12) and a year as int. Given those two values, I have to determine the date range of that month. So I need a datetime variable to represent the first day of that month, and another datetime variable to represent the last day of that month. Is there a fairly easy way to get this info?


Solution

  • DECLARE @Month int
    DECLARE @Year int
    
    set @Month = 2
    set @Year = 2004
    
    select DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0)) /*First*/
    
    select DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0))) /*Last*/
    

    But what do you need as time component for last day of the month? If your datetimes have time components other than midnight you may well be better off just doing something like

    WHERE COL >= DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0)) 
         AND COL < DATEADD(month,@Month,DATEADD(year,@Year-1900,0)) 
    

    In this way your code will continue to work if you eventually migrate to SQL Server 2008 and the greater precision datetime datatypes.