Avatar of James Murphy
James Murphy
Flag for Australia asked on

2 dates in a SQL stored proc - 7 days prior and 30 days in future

Hi,

I have a new for 2 dates in my SQL stored procedure.  
1) 7 Days prior to today
2) 30 days in the future from today.

I am using these, but they don't seem to be working:
      DECLARE @7daysago DATE = CONVERT(DATE, DATEADD(DAY, -DAY(GETDATE()) -7, DATEADD(MONTH, 1, GETDATE())));
      DECLARE @30daysinfuture DATE = CONVERT(DATE, DATEADD(DAY, -DAY(GETDATE()) +30, DATEADD(MONTH, 1, GETDATE())));

Could anyone please point me in the right direction?

cheers
Microsoft SQL ServerSQL

Avatar of undefined
Last Comment
PortletPaul

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
slightwv (䄆 Netminder)

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
James Murphy

ASKER
that is perfect.  Many thanks!
slightwv (䄆 Netminder)

Glad to help.

If you want a slightly different way that is probably more mainstream:
select getdate() as today, dateadd(day,-7,getdate()) as seven_days_ago, dateadd(day,30,getdate()) as thirty_days_from_now
PortletPaul

be careful using getdate() because it is actually the current date AND time, you can use cast(getdate() as date) to set the time to 00:00:00

select
  cast(getdate() as date) as today
, cast(getdate() as date) -7  as seven_days_ago
, cast(getdate() as date) +30 as thirty_days_from_now

Using integers for addition isn't common in TSQL coding, instead  using dateadd() is more common, i.e.

select
  cast(getdate() as date) as today
, dateadd(day,-7,cast(getdate() as date) ) as seven_days_ago
, dateadd(day,30,cast(getdate() as date) ) as thirty_days_from_now

These will also work:

 CONVERT(DATE, DATEADD(DAY, -7, GETDATE()))
 CONVERT(DATE, DATEADD(DAY, +30, GETDATE()))

[edit]
looking back at your originals it seems that you felt it necessary to alter the day and the month - individually - when using DATEADD(). Hopefully you can see that this isn't needed, dateadd() will accurately add or deduct the number of time units from a parameter datetime value.

If in doubt on how to use a function, books online will help: e.g.
https://docs.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql?view=sql-server-2017
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes