Postgres忽略插入错误并继续执行

时间:2016-10-03 08:55:46

标签: postgresql

我有一个PostgeresDB具有以下约束:

  CONSTRAINT "Car_Data_3PM_pkey" PRIMARY KEY ("F_ID", "Date"),
  CONSTRAINT "Car_Data_3PM_F_ID_fkey" FOREIGN KEY ("F_ID")
      REFERENCES "Bike_Data" ("F_ID") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION

当我尝试使用以下方法插入多个值时:

INSERT INTO "Car_Data_3PM" ("F_ID","Date","Price_Type","O","H","L","LT","EQ","V","NAD") VALUES (38,'2016-10-02 08:19:40.056679','x',0,0,0,112.145,0,0,112.145),(14,'2016-10-02 08:19:40.056679','x',0,0,0,5476,0,0,5476),(13,'2016-10-02

我收到此错误:

  

错误:在表“Car_Data_3PM”上插入或更新违反外键   约束“Car_Data_3PM_F_ID_fkey”SQL状态:23503详细信息:密钥   表“Bike_Data”中不存在(F_ID)=(38)。

没有插入行。

如何让Postgres错过约束有问题的行?即插入大部分?

2 个答案:

答案 0 :(得分:1)

你不能让Postgres忽略这些值,但是你可以重写你的语句以不插入那些行:

INSERT INTO "Car_Data_3PM" ("F_ID","Date","Price_Type","O","H","L","LT","EQ","V","NAD") 
select *
from (
   VALUES
     (38,'2016-10-02 08:19:40.056679','x',0,0,0,112.145,0,0,112.145),
     (14,'2016-10-02 08:19:40.056679','x',0,0,0,5476,0,0,5476),
     ... -- all other rows
) as x (id, date, price_type, o, h, l, lt, eq, v nad)
where exists (select 1 
              from "Bike_Data" bd
              where bd."F_ID" = x .id)

答案 1 :(得分:1)

一种方法是编写一个过滤掉错误值的触发器,如下所示:

CREATE FUNCTION car_insert_filter() RETURNS trigger
   LANGUAGE plpgsql AS
$$BEGIN
   IF EXISTS(SELECT 1 FROM "Bike_Data" WHERE "F_ID" = NEW."F_ID")
   THEN
      RETURN NEW;
   ELSE
      RAISE NOTICE 'Skipping row with "F_ID"=% and "Date"=%',
         NEW."F_ID", NEW."Date";
      RETURN NULL;
   END IF;
END;$$;

CREATE TRIGGER car_insert_filter
   BEFORE INSERT ON "Car_Data_3PM" FOR EACH ROW
   EXECUTE PROCEDURE car_insert_filter();