仅在不存在2个值的情况下插入

时间:2018-10-08 14:08:44

标签: postgresql unique-values

我有一张这样的桌子:

CREATE TABLE pratica
(
  progressivo text NOT NULL DEFAULT nextval('pratica_prog_seq'::regclass),
  commessa text NOT NULL,
  pla_uo text NOT NULL,
  tecnico text,
  pratica text NOT NULL,
  lcl_numero numeric(10,0),
  CONSTRAINT pratica_pkey PRIMARY KEY (progressivo)
)
WITH (
  OIDS=FALSE
);

还有第二个这样的表:

CREATE TABLE verifica_checklist
(
  gid text NOT NULL DEFAULT nextval('verifica_checklist_gid_seq'::regclass),
  progressivo text NOT NULL,
  commessa text NOT NULL,
  pla_uo text NOT NULL,
  tecnico text NOT NULL,
  pratica text NOT NULL,
  lcl_numero numeric(10,0),
  tipo_check text NOT NULL,
  data text NOT NULL,
  CONSTRAINT verifica_checklist_pkey PRIMARY KEY (gid)
)
WITH (
  OIDS=FALSE
);

我想创建一个触发器,在满足以下条件时将新行插入表verifica_checklist中:

new.prev_check_ok = 'Si' AND new.prev_check IS NULL

我编写了此函数和此触发器,但是每次更改某个值时,即使已经存在,它也会在表verifica_checklist中插入新行。

CREATE OR REPLACE FUNCTION checklist_verifica()
  RETURNS trigger AS
$BODY$
BEGIN
CASE
WHEN (new.prev_check_ok = 'Si' AND new.prev_check IS NULL) THEN 
INSERT INTO verifica_checklist(progressivo,commessa,pla_uo,tecnico,pratica,tipo_check,data) 
VALUES (NEW.progressivo, NEW.commessa, NEW.pla_uo, NEW.tecnico, NEW.pratica,'Preventivo',current_date);
ELSE NULL;
END CASE;
RETURN NEW;
END
$BODY$
  LANGUAGE plpgsql VOLATILE

CREATE TRIGGER checklist_verifica
  AFTER INSERT OR UPDATE
  ON pratica
  FOR EACH ROW
  WHEN (((((((new.prev_check_ok = 'Si'::text) AND (new.prev_check IS NULL)) OR ((new.sal1_check_ok = 'Si'::text) AND (new.sal1_check IS NULL))) OR ((new.sal2_check_ok = 'Si'::text) AND (new.sal2_check IS NULL))) OR ((new.servitu_check_ok = 'Si'::text) AND (new.servitu_check IS NULL))) OR ((new.def_check_ok = 'Si'::text) AND (new.def_check IS NULL))))
  EXECUTE PROCEDURE checklist_verifica();

唯一值是列progressivo和列tipo_check中的值。 我可以有更多行,它们具有相同的progressivo值,但只能具有不同的tipo_check列值。 我该如何解决?谢谢

0 个答案:

没有答案