PostgreSQL触发器根据条件添加/删除数据

时间:2017-07-31 05:07:18

标签: sql postgresql

我在一个看似简单的部分寻求帮助,比如根据某些条件将数据插入另一个表中。 所以重点是: 有两个表: 人员:

CREATE TABLE "public"."persons" ( 
    "id" Integer DEFAULT nextval('person_id_seq'::regclass) NOT NULL,
    "surname" Character Varying( 100 ) NOT NULL,
    "name" Character Varying( 100 ) NOT NULL,
    "patronymic" Character Varying( 100 ),
    "date_birth" Date NOT NULL,
    "place_birth" Character Varying( 1000 ) NOT NULL,
    "parent_id" Integer,
    "surnamepat" Character Varying,
    "surnamepat_short" Character Varying,
    PRIMARY KEY ( "id" ) );

法律代表的历史:

CREATE TABLE "public"."history_legal_representatives" ( 
    "id" Integer DEFAULT nextval('history_legal_representative_id_seq'::regclass) NOT NULL,
    "person_id" Integer NOT NULL,
    "person_parent_id" Integer NOT NULL,
    "modified" Date DEFAULT ('now'::text)::date,
    PRIMARY KEY ( "id" ) );

在哪里:

"person_id" - persons (at table Persons is ID)
"person_parent_id" - legal representative (at table Persons is parent_id)

我正在尝试做什么:

添加到记录的表,未指定哪个parent_id时,我们只需添加此条目,如果指定了parent_id,则添加 history_legal_representatives 记录: - person_id:= persons.id和person_parent_id:= persons.parent_id。

在表中编辑记录时,如果parent_id的值变为NULL,则从 history_legal_representatives 中删除这样的一对。 (如果这样的逻辑不正确,请说明为什么\更正确)

代码:

添加

CREATE TRIGGER addrep BEFORE INSERT ON "public"."persons" FOR EACH ROW EXECUTE PROCEDURE addrepresentative()[/SRC]

CREATE OR REPLACE FUNCTION public.addrepresentative()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
BEGIN
    if NEW.parent_id != NULL then
    insert into history_legal_representatives (person_id, person_parent_id) 
    values (NEW.id, NEW.parent_id);
    end if;
    RETURN NEW;
END;
$function$

删除

CREATE TRIGGER delrep BEFORE UPDATE ON "public"."persons" FOR EACH ROW EXECUTE PROCEDURE delrepresentative()

CREATE OR REPLACE FUNCTION public.delrepresentative()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
BEGIN
    if NEW.parend_id = null then
    delete from history_legal_representatives where id = NEW.id;
    end if;
    RETURN NEW;
END;
$function$

1 个答案:

答案 0 :(得分:0)

由于SQL中的NULL比较有不同的语法(在delrepresentative中为+ typo)而在删除函数中你想要删除person_id

固定代码:

CREATE OR REPLACE FUNCTION public.addrepresentative()
  RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
    if NEW.parent_id IS NOT NULL then
    insert into history_legal_representatives (person_id, person_parent_id) 
    values (NEW.id, NEW.parent_id);
    end if;
    RETURN NEW;
END;
$function$

CREATE OR REPLACE FUNCTION public.delrepresentative()
  RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
    if NEW.parent_id IS null then
    delete from history_legal_representatives where person_id = NEW.id;
    end if;
    RETURN NEW;
END;
$function$

检查文档https://www.postgresql.org/docs/9.6/static/sql-createtrigger.html,我认为在这种情况下您需要AFTER个触发器