根据间隔和持续时间插入行的函数(触发器)

时间:2018-02-22 12:42:21

标签: postgresql

我有一个schedule表,如下所示:

ScheduleId::uuid | Start::timestamptz(now()) | SlotSize::int(minutes) | Interval::int(days)

slot表如下:

SlotId::uuid | ScheduleId::uuid | Start::timestamptz | End::timestamptz 

我想根据计划表上的触发器自动插入插槽。

到目前为止,我有:

create
    trigger create_slots after insert
        on
        schedule for each row execute procedure create_new_slots();

create or replace function create_new_slots() 
returns trigger 
language plpgsql 
as $function$ 
  begin
-- in a loop determine how many slots there are, then insert each one
    insert into slot
      select
        uuid_generate_v4(),
        new."ScheduleId",
        start, -- need to determine the start time of each instance of slot
        end -- need to determine the end time of each instance of slot
-- end loop
  end return new;
end $function$

我需要以某种方式将它放入光标并计算插槽数以及每个插槽的开始和结束时间。

我正在使用PostgreSQL 10

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

好的,所以我需要的是基于[开始]时间(四舍五入到小时),结束时间(即[开始]时间+天数的[PlanningHorizo​​n])生成一个系列和[SlotSize]。然后遍历这个系列并将每个时隙插入我的[Slot]表:

CREATE OR REPLACE FUNCTION create_new_slots()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
declare
    slot timestamptz;
begin
    for slot in select generate_series(
        date_trunc('hour', new."Start")::timestamptz, 
        (new."Start" + interval '1' day * new."PlanningHorizon")::timestamptz,
        new."SlotSize" * '1 minutes'::interval)
    loop
        insert into slot select uuid_generate_v4(), new."ScheduleId", slot, slot + new."SlotSize" * '1 minutes'::interval;
    end loop;
return NEW;
end
$function$