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

后端 未结 9 1063
忘了有多久
忘了有多久 2020-12-30 08:29

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 d

9条回答
  •  心在旅途
    2020-12-30 09:16

    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.

提交回复
热议问题