SQL Raise Application Error Trigger

放肆的年华 提交于 2019-12-20 04:55:14

问题


This is throwing "Error: ORA-04082: NEW or OLD references not allowed in table level triggers"

I'm not sure where I'm going wrong. The error number shouldn't make a difference should it?

    CREATE OR REPLACE TRIGGER REJECTION 
BEFORE INSERT OR UPDATE ON TEA_PREFS_T 
DECLARE temp NUMBER;
BEGIN
  SELECT COUNT(*) INTO temp FROM tea_prefs_t WHERE person = :new.drinkerid;
  IF (temp >=10) THEN
    raise_application_error(-20101, 'ERROR: CANNOT INSERT MORE THAN 10');
    ROLLBACK;
  END IF;
END;

回答1:


As the error suggests, you can only refer to the new and old pseudo-rows in a row-level trigger, not a table-level trigger, which fires once regardless of how many rows were affected by the statement. If you updated two rows with different drinker IDs, which value would the trigger use for its look-up?

To make it a row-level trigger, add FOR EACH ROW:

CREATE OR REPLACE TRIGGER REJECTION 
BEFORE INSERT OR UPDATE ON TEA_PREFS_T 
FOR EACH ROW
DECLARE
  temp NUMBER;
BEGIN
  SELECT COUNT(*) INTO temp FROM tea_prefs_t WHERE person = :new.drinkerid;
  IF (temp >=10) THEN
    raise_application_error(-20101, 'ERROR: CANNOT INSERT MORE THAN 10');
  END IF;
END;
/

You can't commit or rollback from within a trigger; it's up to the transaction doing the insert/update to decide whether to do that.

However, you also can't select from the same table you're inserting into/updating; you'll get a mutating table error from this, at least if you attempt to insert/update multiple rows at once.



来源:https://stackoverflow.com/questions/28701692/sql-raise-application-error-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!