求一个触发器的写法
现在有一张表Table1,其中包含一个INT型字段ColInt和外键字段ColFK。现在需要编写一个触发器,当子表执行INSERT操作后,在子表中查找所有外键字段的值等于新增记录的外键字段的值的记录,将这些记录中ColInt字段中值为最小的那条记录更新到另外一张表Table2中。我自己写的UPDATE语句为:
UPDATE TABLE2 SET (Col1,Col2) =
(SELECT Col1,Col2 FROM
(SELECT ColFK,Col1,Col2,
ROW_NUMBER() OVER (PARTITION BY ColFK ORDER BY ColInt) RN
FROM Table1
WHERE ColFK = 33709) TB
WHERE RN = 1)
WHERE ColFK = 33709
这个UPDATE语句在执行的时候能获得所希望的结果。现在我计划把这个UPDATE语句写成一个触发器,如下:
CREATE OR REPLACE TRIGGER TIG1 AFTER UPDATE ON TABLE1 FOR EACH ROW
BEGIN
UPDATE TABLE2 SET (Col1,Col2) =
(SELECT Col1,Col2 FROM
(SELECT ColFK,COL1,Col2,
ROW_NUMBER() OVER (PARTITION BY ColFK ORDER BY ColInt) RN
FROM Table1
WHERE ColFK = :NEW.ColFK) TB
WHERE RN = 1)
WHERE ColFK = :NEW.ColFK
END;
/
这个触发器中存在语法错误。小弟第一次尝试写触发器,完全找不到门道,因此想请教各位高手问题出在哪里,还请各位不吝赐教,小弟先行谢过
------解决方案--------------------应该是insert触发器吧,把你的标结构发出来
CREATE OR REPLACE TRIGGER TIG1
AFTER insert ON TABLE1
FOR EACH ROW
BEGIN
UPDATE TABLE2 SET (Col1,Col2) =
(SELECT Col1,Col2 FROM
(SELECT ColFK,COL1,Col2,
ROW_NUMBER() OVER (PARTITION BY ColFK ORDER BY ColInt) RN
FROM Table1
WHERE ColFK = :NEW.ColFK) TB
WHERE RN = 1)
WHERE ColFK = :NEW.ColFK
END;
------解决方案--------------------CREATE OR REPLACE TRIGGER TIG1 AFTER UPDATE ON TABLE1 FOR EACH ROW
BEGIN
UPDATE TABLE2 SET (Col1,Col2) =
(SELECT Col1,Col2 FROM
(SELECT ColFK,COL1,Col2,
ROW_NUMBER() OVER (PARTITION BY ColFK ORDER BY ColInt) RN
FROM Table1
WHERE ColFK = :NEW.ColFK) TB
WHERE RN = 1)
WHERE ColFK = :NEW.ColFK;
END;
/