我的Oracle Trigger出了什么问题?

时间:2011-12-07 19:44:50

标签: sql oracle triggers

CREATE OR REPLACE TRIGGER Net_winnings_trigger
  AFTER UPDATE OF total_winnings ON Players
  FOR EACH ROW
DECLARE
  OldTuple OLD
  NewTuple NEW
BEGIN
  IF(OldTuple.total_winnings > NewTuple.total_winnings)
  THEN
    UPDATE Players
    SET total_winnings = OldTuple.total_winnings
    WHERE player_no = NewTuple.player_no;
 END IF;
END;
/

我试图获得一个触发器,只允许'total_winnings'字段更新为大于当前值的值。

如果更新值更小,触发器应该将设置值保留为旧值(就好像更新永远不会发生一样)

2 个答案:

答案 0 :(得分:3)

由于您要覆盖UPDATE语句中指定的值,因此您需要使用BEFORE UPDATE触发器。像这样的东西

CREATE OR REPLACE TRIGGER Net_winnings_trigger
  BEFORE UPDATE OF total_winnings ON Players
  FOR EACH ROW
BEGIN
  IF(:old.total_winnings > :new.total_winnings)
  THEN
    :new.total_winnings := :old.total_winnings;
  END IF;
END;

但是覆盖UPDATE语句中指定的值是一个危险的游戏。如果这是不应该发生的事情,那么你真的应该提出错误,以便应用程序可以意识到存在问题。否则,您正在为应用程序创建各种可能的错误决策。

答案 1 :(得分:0)

这样的东西应该可以工作..虽然如果你试图更新到更小的值,它将隐藏更新没有发生的事实。对于用户来说,一切看起来都有效,但数据将保持不变。

CREATE OR REPLACE TRIGGER Net_winnings_trigger
BEFORE UPDATE OF total_winnings
ON Players
FOR EACH ROW
DECLARE
BEGIN
    :new.total_winnings := greatest(:old.total_winnings,:new.total_winnings);
END;