存储过程,访问刚刚插入的数据

时间:2016-04-26 03:24:58

标签: postgresql stored-procedures triggers

我正在尝试根据插入另一个表的人将值插入表中。我有一个触发器,当有人被分配给员工时,他们会自动被分配到employeesepark,并获得第一个可用的点。我无法弄清楚如何访问正在输入到employee表的id。我很感激任何提示或想法,谢谢!

这是我收到的错误。

ERROR:  record "new" is not assigned yet
create or replace function new_employeeAssign() returns trigger as $new_employeeAssign$
declare 
    open_spotID int := (select parkingspot.spotid  
                        from employeepark e full outer join parkingspot on e.spotid = parkingspot.spotid
                        where e.spotid isNull limit 1);
begin 
    insert into employeepark(employeeid, spotid)
        values(new.employeeid ,open_spotID);
End;
$new_employeeAssign$ language plpgsql;

create trigger new_employeeAssign after insert on employee
   execute procedure new_employeeAssign();

insert into people(peopleid, fname, lname)
    values(686, 'random', 'person');
insert into employee(employeeid)
    values(686);
帕特里克现在为我想出了这个问题,我遇到了这个问题: 我想从所有这些范围中选择第一个值为null的值,我不断回过头,它只是绕过范围并直接进入isNull。

    (select parkingspot.spotid  
    from employeepark e full outer join parkingspot on e.spotid =     parkingspot.spotid
    where  (e.spotid = 301) 
    or (e.spotid = 1601) 
    or (e.spotid = 2001) 
    or (e.spotid = 2011) 
    or (e.spotid = 2121) 
    or (e.spotid = 2021) 
    or (e.spotid = 2771) 
    or (e.spotid = 2921) 
    or (e.spotid = 3021) 
    or (e.spotid = 3823) isNull
    limit 1)

1 个答案:

答案 0 :(得分:2)

您的触发器定义不正确。默认情况下,触发器适用于FOR EACH STATEMENT,然后NEW参数不存在(毕竟触发器不适用于行)。相反,你应该:

CREATE TRIGGER new_employeeAssign AFTER INSERT ON employee
FOR EACH ROW EXECUTE PROCEDURE new_employeeAssign();

您的触发器功能也存在一些问题,尤其是分配给变量open_spotID的查询。此查询将始终选择NULL,因为e.spotid IS NULL并且您加入了e.spotid = parkingspot.spotid。您正在寻找的逻辑可能是您希望通过在表employeepark中使用尚未分配给其他员工的spot_id的行来为新员工分配停车位。请参阅下面的代码。

您还需要RETURN NEW来自该功能。

除此之外,您的触发器功能可以如此优化:

CREATE FUNCTION new_employeeAssign() RETURNS trigger AS $new_employeeAssign$
BEGIN
    INSERT INTO employeepark(employeeid, spotid)
        SELECT NEW.employeeid, spotid  
        FROM parkingspot p
        LEFT JOIN employeepark e USING (spotid)
        WHERE e.employeeid IS NULL
        LIMIT 1;
    RETURN NEW;
END;
$new_employeeAssign$ LANGUAGE plpgsql;