0

I am having trouble with creating a table in oracle SQL.

I was looking to have a column called DEFAULTRULE. Only 1 row in this column can be '1' at any given time. So for example

ID    DEFAULTRULE
1     0
2     0
3     1

If I was to update ID 2 to have default rule = 1 then it would either set ID 3 default rule to 0

or

throw an error (I don't really mind as long as there is only one '1')

I have tried to create triggers to do both but keep getting the

ORA-04091 table is mutating, trigger/function may not see it.

2 of my attempts:

CREATE OR REPLACE TRIGGER CHECKDEFAULTRULE
  BEFORE UPDATE ON BUSINESS_RULE
  FOR EACH ROW
DECLARE 
v_count NUMBER(1);
BEGIN 
  IF :NEW.DEFAULTRULE = 1 THEN
      SELECT COUNT(DEFAULTRULE)INTO v_count FROM BUSINESS_RULE WHERE DEFAULTRULE = 1;
      IF v_count != 0 THEN
       RAISE_APPLICATION_ERROR(-20000,'BUSINESS_RULE already has a default rule. Please set this to 0 and try again');
      END IF;  
   END IF;
END;

and

CREATE OR REPLACE TRIGGER CHECKDEFAULTRULE
BEFORE UPDATE ON BUSINESS_RULE
FOR EACH ROW
BEGIN 
IF :new.DEFAULTRULE = 1 THEN
   UPDATE BUSINESS_RULE
   SET    DEFAULTRULE = 0;
   WHERE  DEFAULTRULE = 1; 
END IF;
END checkDefaultForOne;

Would anyone be able to point me in the right direction? Thanks in advance. Jon

4

1 回答 1

1

你不需要触发器。
使用基于表达式的唯一索引:

CREATE UNIQUE INDEX someindex ON sometable( 
  CASE WHEN DEFAULTRULE = 1
       THEN 1
  END
  );

请参阅此演示:http
: //sqlfiddle.com/#!4/2431a 它允许插入许多 DEFAULTRULE != 1,但只有一个 DEFAULTRULE = 1
尝试在此演示中附加附加值INSERT INTO sometable VALUES( 1,1);,您将收到错误消息。

于 2014-11-06T17:22:54.240 回答