Is it possible to use values from another table as the interval in a DATEADD function?

杀马特。学长 韩版系。学妹 提交于 2020-01-16 08:48:27

问题


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)

回答1:


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



回答2:


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

SQLFiddle




回答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
WHERE date IN (
    SELECT DATEADD(D,daysBefore,DATEADD(D, 0, DATEDIFF(D, 0, GETDATE())))
    FROM interval
    WHERE events.customerID = customerID);

SQLFiddle



来源:https://stackoverflow.com/questions/13001876/is-it-possible-to-use-values-from-another-table-as-the-interval-in-a-dateadd-fun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!