我在看似簡單的部分尋求幫助,例如根據某些條件將數據插入到另一個表中。 所以問題是: 有兩個表: 人: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$
需要什麼要與代碼做任何錯誤? –