我正试图让这个触发器起作用:
CREATE TRIGGER Transaction_insert BEFORE INSERT ON Transaction
FOR EACH ROW WHERE Number = NEW.AccountNumber
IF Account.CreditBalance + NEW.Amount < Account.CreditLimit THEN
UPDATE Account SET CreditBalance = CreditBalance + NEW.Amount where Number = NEW.AccountNumber;
ELSE
SET NEW.Valid = 0
END IF;
这是我从myPHPAdmin获得的错误。
答案 0 :(得分:0)
这就是我认为你想要的,假设Account
到Transaction
是Number
/ AccountNumber
上的1:N关系:
DELIMITER //
-- Assumptions:
-- 1. Transaction.AccountNumber is F.K. REFERENCES Account(Number)
-- 2. Account.Number is UNIQUE
--
CREATE TRIGGER trg_bi_transaction BEFORE INSERT ON Transaction
FOR EACH ROW
BEGIN
-- Adjust account balance (if permitted)
--
UPDATE Account
SET CreditBalance = CreditBalance + NEW.Amount
WHERE Number = NEW.AccountNumber
AND
(CreditBalance + NEW.Amount) < CreditLimit;
-- Was the adjustment valid/permitted?
--
SET NEW.Valid = (ROW_COUNT() = 1);
END //
DELIMITER ;
如果Account
允许,该触发器将尝试为任何给定的Transaction
更新正确的CreditLimit
。如果UPDATE成功,Valid
字段将设置为1,如果不成功则设置为0。
MySQL触发器不支持触发级WHERE子句。在触发器主体内移动Number / NEW.AccountNumber检查。
答案 1 :(得分:0)
您的IF需要是一个完整的SELECT来引用另一个表(Account
)
IF EXISTS (SELECT * FROM `Account` A
WHERE A.CreditBalance + NEW.Amount < A.CreditLimit AND
A.Number = NEW.AccountNumber) THEN
UPDATE ...
编辑:这是你的第二个重复答案
在这种情况下,请删除FOR FOR EACH ROW后的WHERE