Search code examples
sqlsql-serversql-server-2012sql-server-2012-express

How to Target Last Month in SQL Query


I'm using this code in an SQL query

WHERE [Date] >= DATEFROMPARTS(DATEPART(year,GETDATE()),DATEPART(month,GETDATE())-1,DATEPART(day,GETDATE()))
  AND [Date] <= EOMONTH(DATEFROMPARTS(DATEPART(year,GETDATE()),DATEPART(month,GETDATE())-1,DATEPART(day,GETDATE())));

The problem is come 2020 the December query will through up an error

The code I posted manages the dates between which data will be returned. It looks at the date the code is run and choose that day from last month till the end of last month. What I need is dates from the 1st till the last day of the month prior to the one this code is called in.

I will be working on this issue tomorrow, it will be interesting to see what solutions other people can come up with.


Solution

  • If you want the previous month:

    where date >= dateadd(month, -1, datefromparts(year(getdate(), month(getdate(), 1))) and
          date < datefromparts(year(getdate(), month(getdate(), 1))
    

    This simply checks that it is before the first of the this month and then subtracts a month from that.