【问题标题】:Trigger on UPDATE to DELETE rows in another table depending on a third table根据第三个表触发 UPDATE 以删除另一个表中的行
【发布时间】:2016-10-23 19:04:53
【问题描述】:

我正在尝试为以下表格创建触发器:

CREATE TABLE public.first (
 userid bigint,
 name varchar
);

 CREATE TABLE public.second (
 userid bigint,
 companyid bigint
);

CREATE TABLE public.visibility_matrix (
 name varchar,
 companyid bigint
);

每当更新表first 中的一行时,触发器应采用userid 并在表second 中搜索相同的userid。如果存在,则从visibility_matrix 中删除行/行,其中companyid 是从表“second”中提取的。

这是我尝试过的:

触发功能:

CREATE OR REPLACE FUNCTION pos_org_rel_refresh()
  RETURNS trigger AS  
$$  
DECLARE
  r Integer ;

BEGIN  

 IF TG_OP='UPDATE' THEN

DELETE FROM visibility_matrix where companyid=NEW.companyid;
RETURN NEW;

  END IF;
END;
$$  
LANGUAGE 'plpgsql';  

触发器:

CREATE TRIGGER test_trigger  
AFTER UPDATE 
ON first
FOR EACH ROW  
EXECUTE PROCEDURE pos_org_rel_refresh();

【问题讨论】:

  • 那么你有答案了吗?

标签: postgresql triggers plpgsql sql-delete


【解决方案1】:

使用USING clause of DELETE 加入另一个表:

触发功能:

CREATE OR REPLACE FUNCTION pos_org_rel_refresh()
  RETURNS trigger AS  
$func$
-- DECLARE
--    r int;  -- not used in function body
BEGIN  
-- IF TG_OP='UPDATE' THEN  -- redundant while func is only used in AFTER UPDATE trigger
   DELETE FROM public.visibility_matrix v
   USING  public.second s
   WHERE  s.userid = NEW.userid
   AND    v.companyid = s.companyid;
-- END IF;

RETURN NEW;  --  and don't place this inside the IF block either way

END
$func$  LANGUAGE plpgsql;  -- don't quote the language name

触发器:

CREATE TRIGGER test_trigger  
AFTER UPDATE ON first
FOR EACH ROW EXECUTE PROCEDURE pos_org_rel_refresh();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多