简体   繁体   English

PLSQL插入并使用触发器更新另一个表

[英]PLSQL Insert and update another table with trigger

I am new to plsql; 我是plsql的新手; I have 2 tables, tableA and tableB. 我有2个表,tableA和tableB。

tableA is my main table. tableA是我的主表。 After insert or update on tableA I want to update it with its related table. 在tableA上插入或更新后,我想用其相关表对其进行更新。

For example: tableA has the column named 'GID_FROM_B' and tableB has the column named 'GID'. 例如:tableA的列名为“ GID_FROM_B”,而tableB的列名为“ GID”。 I can match this table's values with id and counter. 我可以将此表的值与id和counter匹配。 According to below table I want to add values of (2, 5, '') to tableA from my interface. 根据下表,我想从我的界面向tableA添加(2,5,'')值。 And gid_from_b will be updated with trigger. 并且gid_from_b将使用触发器更新。 And I wrote the trigger below. 我在下面编写了触发器。

tableA:
id     |   counter  |   gid_from_b  |
1             3            xyz                            


tableB:
id     |   counter  |      gid      |
1             3            xyz                            
2             5            abc 

CREATE OR REPLACE TRIGGER gid_update
AFTER INSERT OR UPDATE ON DBO.TABLEA
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW

UPDATE TABLEA
   SET GID_FROM_B =  TABLEB.GID
   WHERE TABLEA.ID = TABLEB.ID AND TABLEA.COUNTER = TABLEB.COUNTER;
END;

For only INSERT operation to be performed, we need to replace AFTER INSERT OR UPDATE with BEFORE INSERT , where not possible to create an AFTER INSERT TRIGGER with :new prefixed columns. 对于仅要执行的INSERT操作,我们需要用BEFORE INSERT替换AFTER INSERT OR UPDATE ,如果不可能用:new前缀列创建AFTER INSERT TRIGGER

The following suits well for your aim : 以下内容非常适合您的目标:

CREATE OR REPLACE TRIGGER gid_update
BEFORE INSERT ON TableA
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN 
  for c in ( select b.gid from tableB b where b.id = :new.id and b.counter = :new.counter )
  loop
    :new.gid_from_b := c.gid; 
  end loop; 
END;

You don't need to run any update statement, simply use a select into :NEW.gid_from_b. 您无需运行任何更新语句,只需在:NEW.gid_from_b中使用选择即可。 Note that it should be a BEFORE UPDATE TRIGGER if you want to modify values of :NEW columns. 请注意,如果要修改:NEW列的值,则应为“ BEFORE UPDATE TRIGGER

This assumes that your TableB has a single row for each id,counter combination. 假设您的TableB的每个ID,计数器组合只有一行。 If not, you may have to fetch MAX(gid) MIN(gid) or whatever suits you. 如果不是,则可能必须获取MAX(gid) MIN(gid)或适合您的任何东西。

CREATE OR REPLACE TRIGGER gid_update
   BEFORE INSERT OR UPDATE ON TABLEA
FOR EACH ROW WHEN (NEW.gid_from_b IS NULL)
BEGIN
 SELECT gid INTO 
    :NEW.gid_from_b FROM tableB b 
  WHERE b.id =:NEW.id AND b.counter = :NEW.counter;
END;
/

dbfiddle dbfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM