如何在Oracle SQL中触发以更改另一个表中的行

时间:2018-12-12 01:25:37

标签: sql oracle triggers

我需要在我的SQL代码中编写一个触发器,以更改与表B(Historia_Zamowien)相关联的表A(Asortyment)中的值,关系为多对多。要连接A和B,我使用表C(Zamowienia_Asortyment)。

How it looks like in relational model

我需要在Asortyment.Dostepnosc之后通过Zamowienia_Asortyment到达INSERT ON Historia_Zamowien,并将值更改为0。我写了一些行不通的代码,我不知道出什么问题了。你能帮忙吗?

CREATE TRIGGER "Zmiana_Dostepnosci_Po_Zamowieniu"
AFTER INSERT ON "Historia_Zamowien"
FOR EACH ROW
BEGIN
    UPDATE "Asortyment"
    SET tab1."Dostepnosc" = 0
    FROM "Asortyment" tab1 JOIN "Zamowienia_Asortyment" tab2 ON tab1."ID_sprzetu" = tab2."ID_sprzetu"
         JOIN inserted tab3 ON tab2."Numer_zamowienia" = tab3."Numer_zamowienia"
    WHERE tab1."ID_sprzetu" = tab2."ID_sprzetu" AND tab2."Numer_zamowienia" = inserted."Numer_Zamowienia"
END;
/

运行代码后,我得到:

Error(1,5): PL/SQL: SQL Statement ignored
Error(3,5): PL/SQL: ORA-00933: SQL command not properly ended
Error(7): PLS-00103: Endountered symbol "end-of-file" when expecting one of the following:     ( begin case declare end exception exit for goto if loop mod    null pragma raise return select update while with    <an identifier> <a double-quoted delimited-identifier>    <a bind variable> << continue close current delete fetch lock    insert open rollback savepoint set sql execute commit forall    merge pipe purge json_exists json_value json_query    json_object json_array 

1 个答案:

答案 0 :(得分:1)

您的SQL存在几个问题:

  • 在Oracle中,您不能在JOIN中使用UPDATE;我将其替换为WHERE EXISTS相关子查询
  • 您在JOINWHERE子句中有重复的条件,我对此进行了简化
  • 要引用Historia_Zamowien中新插入的行,请使用:NEW关键字(您似乎使用了inserted

尝试:

CREATE TRIGGER "Zmiana_Dostepnosci_Po_Zamowieniu"
AFTER INSERT ON "Historia_Zamowien"
FOR EACH ROW
BEGIN
    UPDATE "Asortyment" tab1 SET tab1."Dostepnosc" = 0
    WHERE EXISTS (
        SELECT 1
         FROM "Zamowienia_Asortyment" tab2 
         WHERE tab2."ID_sprzetu" = tab1."ID_sprzetu"
         AND tab2."Numer_zamowienia" = NEW."Numer_Zamowienia"
    )
END
/