Bring today’s date records up to 1 month ago SQLSERVER

Asked

Viewed 462 times

0

How do I get today’s date records up to 1 month ago on SQLSERVER?

I know that for example, with 7 days, use GETDATE()-7. But and for 1 month, as would be?

  • How is the column containing the date declared: date? datetime? datetime2? ...

  • Tried to DATEADD(month, -1, GETDATE()) ?

2 answers

1

You can use the DATEADD, this query will return the date in the last month starting from the last midnight

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, DAY(GETDATE())-1)

0

How do I get today’s date records up to 1 month ago on SQLSERVER?

I suggest you use the function DATEDIFF.

-- código #1
declare @UmMêsAtrás date;
set @UmMêsAtrás= datediff (month, -1, cast (current_timestamp as date));

--
SELECT ...
  from ...
  where coluna_data >= @UmMêsAtrás;

It is necessary to be careful to avoid the implicit conversion in the WHERE clause; thus, the @Ummêsago variable must be declared in the same type of data coluna_data. Details in the article The dangers of implicit conversion

Browser other questions tagged

You are not signed in. Login or sign up in order to post.