我在看似简单的部分寻求帮助,例如根据某些条件将数据插入到另一个表中。 所以问题是: 有两个表: 人: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$
需要什么要与代码做任何错误? –