Is it possible to use values from another table as the interval in a DATEADD function?
-
13-07-2021 - |
Question
I have a table of events containing a date (smalldatetime).
I have a table of intervals (int) (days before) for when a reminder should be sent - DATEADD(D, *interval*, GETDATE())
.
I'm trying to write an SQL statement to get all the events where a reminder should be sent today (based on GETDATE()
from the DATEADD function. This is instead of me first getting all the intervals and running SQL in a loop, passing each interval as a parameter into the DATEADD function.
Any ideas how I'd do this?
**dbo.events**
id (int) PK
date (smalldatetime)
customerID (int)
**dbo.intervals**
id (int) PK
daysBefore (int)
customerID (int)
Solution
The answer is yes. I can't draw this query for you due to lack of information provided. But yes, you can.
Take this example:
MyTable:
ID Interval Date
1 1 10-10-2001
SELECT ID, DATEADD(D, Interval, GETDATE()) AS NewDate FROM MyTable
SELECT e.*
FROM [events] e
INNER JOIN [interval] i on e.customerID = i.customerID
WHERE e.date = DATEADD(D, i.daysBefore,
DATEADD(D, 0,
DATEDIFF(D, 0, GETDATE())))
OTHER TIPS
Yes. You should have tried it yourself
create table t(val int);
insert into t values(4),(7),(10)
select DATEADD(D, val, GETDATE()) from t
Thanks everyone for showing how that's possible. I presume this would be how to write the SQL, unless there is a more efficient way?
SELECT *
FROM events
WHERE date IN (
SELECT DATEADD(D,daysBefore,DATEADD(D, 0, DATEDIFF(D, 0, GETDATE())))
FROM interval
WHERE events.customerID = customerID);