0

这是一个有点令人困惑的问题。希望我能用一种有意义的方式来表达它。

在我的 sql server 2008 r2 数据库中,我有一个名为的表expectedTimes,它告诉任务运行的频率以及开始和结束时间。它看起来像下面

| taskID | startTime | endTime | freq |
|________|___________|_________|______|
|    1   |    08:00  |   13:45 |  30  |
|    2   |    00:00  |   23:59 |  15  |
|    3   |    06:35  |   20:20 |  10  |
|    4   |    08:00  |   09:00 |  5   |
|________|___________|_________|______|

我将每 15 分钟运行一次脚本,检查预期运行的任务。返回以下显示该内容的最有效方式是什么8:36。我需要一种有效的方法来执行此操作的原因是表中有 1500 行expecteTimes。必须每 15 分钟乘以多少次才能到达当前时间似乎非常耗费资源

| taskID | expected |
|________|__________|
|    1   |   08:30  |
|    2   |   08:30  |
|    3   |   08:25  |
|    3   |   08:35  |
|    4   |   08:25  |
|    4   |   08:30  |
|    4   |   08:35  |
4

1 回答 1

1

所以我写了这个sql - 希望有用。

create table temp
(
  taskID int,
  starttime time,
  EndTime time,
  freq int 
)
insert into temp (taskID,starttime,EndTime,freq)
select 1   ,    '08:00'  ,   '13:45' ,  30  
union all
select 2   ,    '00:00'  ,   '23:59' ,  15  
union all
select 3   ,    '06:35'  ,   '20:20' ,  10  
union all
select 4   ,    '08:00'  ,   '09:00' ,  5   

    Declare @date datetime
    SELECT @date = Getdate() 

    ;with src as (
    SELECT  
    convert(datetime2(0),cast(cast(getdate() as date) as nvarchar)+' '+cast(starttime as nvarchar),102) startDate,
    convert(datetime2(0),cast(cast(getdate() as date) as nvarchar)+' '+cast(Endtime as nvarchar),102) endDate
    ,* FROM    temp
    )

    SELECT 
    case when @date between startDate and endDate then dateadd(minute,(datediff(minute,startdate,getdate())/freq+1)*15,startDate)
    else dateadd(d,1,startDate) end as NextRun,
    *
    FROM    src
于 2013-04-16T13:08:50.877 回答