【问题标题】:Postgres insert procedure throws foreign key exceptionPostgres插入过程抛出外键异常
【发布时间】:2018-03-21 04:40:44
【问题描述】:

我有两个表 vendor_service_place 和 places.id 作为 vendor_service_table 中的外键。我创建了一个过程,它首先将一个条目插入到位置表中,然后从 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 执行某种批处理,它同时执行这两个语句,这可能是它无法在位置表中找到 id 的原因。有关如何正确执行此操作的任何想法?

【问题讨论】:

标签: postgresql stored-procedures


【解决方案1】:

如果您正在执行多个插入,似乎不建议使用 lastval() 来获取最后一个插入 id。 Postgres not returning lastval() properly。 将 LastVal() 替换为 return id 语句后,程序运行良好。

      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

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 1970-01-01
    • 2017-09-30
    • 2015-12-12
    • 2015-10-17
    • 1970-01-01
    • 2021-03-09
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多