Postgres插入过程抛出外键异常

时间:2018-02-02 07:29:09

标签: postgresql stored-procedures

我有两个表vendor_service_place,其中places.id作为vendor_service_table中的外键。我创建了一个过程,首先将一个条目插入到places表中,然后从LASTVAL()获取该id,并在vendor_service_table中插入一个条目。但是当我执行这个功能时,我正在

insert or update on table "vendor_service_place" violates foreign key 
constraint "fk_places"
DETAIL:  Key (place_id)=(2057) is not present in table "places".
CONTEXT:  SQL function "insert_data" statement 2

这是我的插入程序:

CREATE FUNCTION insert_data(vendorid integer,
                        serviceid integer,
                        name text,
                        address text,
                        latitude text,
                        longitude text,
                        contact_info text,
                        rating numeric,
                        description text) RETURNS bigint AS $$
    INSERT INTO places(name,address,latitude,longitude,contact_info,created_at)
    VALUES (name,address,latitude,longitude,contact_info,current_timestamp);

    INSERT INTO vendor_service_place(vendor_id,service_id,place_id,description,rating,created_at)
    VALUES (vendorid,serviceid,LASTVAL(),description,rating,current_timestamp);
    SELECT LASTVAL() as result;
$$ LANGUAGE SQL;

我怀疑Postgres在同时执行这两个语句的情况下执行某种批处理,这可能是为什么它无法在places表中找到id。关于如何正确地做到这一点的任何想法?

1 个答案:

答案 0 :(得分:0)

如果您正在进行多次插入,则建议不要使用lastval()来获取最后一个插入ID。 Postgres not returning lastval() properly。 用return id语句替换LastVal()后,过程正常工作。

      DECLARE
              insert_id bigint;
      BEGIN
      INSERT INTO places(name,address,latitude,
                         longitude,contact_info,
                         created_at,coordinates)
      VALUES (name,address,latitude,
              longitude,contact_info,
              current_timestamp,
              ST_SetSRID(ST_MakePoint(cast (longitude as numeric),cast (latitude as numeric)),4326))
              returning id into insert_id;

      INSERT INTO vendor_service_place(vendor_id,service_id,place_id,
                                       description,rating,created_at)
      VALUES (vendorid,serviceid,insert_id,
              description,rating,current_timestamp);
      return insert_id;
      END