Skip to content Skip to sidebar Skip to footer

Is It Possible To Use Values From Another Table As The Interval In A Dateadd Function?

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()).

Solution 1:

Yes. You should have tried it yourself

create tablet(val int);
insert into t values(4),(7),(10)

select DATEADD(D, val, GETDATE()) from t

SQLFiddle

Solution 2:

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    IntervalDate1110-10-2001SELECT ID, DATEADD(D, Interval, GETDATE()) AS NewDate FROM MyTable


SELECT e.*FROM [events] e
INNERJOIN [interval] i on e.customerID = i.customerID
WHERE e.date = DATEADD(D, i.daysBefore, 
                   DATEADD(D, 0, 
                       DATEDIFF(D, 0, GETDATE())))

Solution 3:

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
WHEREdateIN (
    SELECT DATEADD(D,daysBefore,DATEADD(D, 0, DATEDIFF(D, 0, GETDATE())))
    FROMintervalWHERE events.customerID = customerID);

SQLFiddle

Post a Comment for "Is It Possible To Use Values From Another Table As The Interval In A Dateadd Function?"