我需要定期將外部資料庫中的資訊上傳到我的資料庫中。這些是我的桌子
CREATE TABLE A
(
id character varying primary key,
name character varying UNIQUE
)
CREATE TABLE B
(
id character varying primary key,
name character varying
)
CREATE TABLE C
(
id character varying REFERENCES B(id),
name character varying REFERENCES A(name)
)
為了增加一些見解,A.name 是已知名稱,B.name 是可能包含或不包含這些已知名稱的文本。匹配項保存在表 c 中。我在上傳表 b 時在 R 中執行此作業,但我需要一個觸發器,只要在 A 中插入一行(更新和洗掉通過級聯解決),就在 C 中插入新匹配項。
我在想這樣的事情(偽代碼):
CREATE TRIGGER trigger_name
AFTER INSERT
ON A FOR EACH ROW
AS
BEGIN
SET NOCOUNT ON;
-- Loop throug all INSERTED.name
-- Search each INSERTED.name value in B.name with: like '%INSERTED.name%'
-- When found, insert in C both id and INSERTED.name
END;
我最大的問題是我無法弄清楚如何在 PLPGSQL 中正確地進行迭代,或者這是否是正確的近似值。只呼叫加載所需表的 R 腳本并再次映射它們而不是使用插入的資料會更好嗎?
如果我的問題不夠清楚,謝謝和抱歉!
uj5u.com熱心網友回復:
示例如何撰寫觸發器函式以及如何為表創建觸發器:
CREATE FUNCTION a_after_insert()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS $$
declare
b_id varchar;
begin
select
id into b_id
from b
where
b."name" like '%' || new."name" || '%';
-- if record not found then b_id will be null;
if (b_id is not null) then
insert into c (id, "name") values (b_id, new."name");
end if;
return new;
END;
$$
create trigger a_after_insert_trigger
after insert
on a
for each row
execute procedure a_after_insert();
對于 PostgreSQL 中的每一行——這意味著即使一次向表中插入 10 條記錄,觸發器也會為每一行作業一次,因此不需要回圈。
只是這里可能有問題,因為我們像在b表中一樣搜索,它的結果可能不是一行而是幾行。如果你愿意,你也可以這樣寫:
CREATE FUNCTION a_after_insert()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS $$
begin
insert into c (id, "name")
select b.id, new.name
from b
where
b."name" like '%' || new."name" || '%';
return new;
END;
$$
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516929.html
上一篇:SQLite中的資料分析:來自經常性銷售(訂閱)的月收入
下一篇:有條件的回圈
