我正在尝试为假数据库创建一个触发器。假设那里 是BANK-BRANCH的名为“total_loan”的派生属性,用于维护每个分支机构的贷款总额。我试图设计一个触发器来维护这个派生属性。因此,我的触发器似乎停止了我的load.sql脚本,如下所示:
CREATE TABLE a2_bankbranch (
name VARCHAR(200) NOT NULL,
branch_num VARCHAR(200) NOT NULL,
address VARCHAR(200) NOT NULL,
routing_code VARCHAR(200) NOT NULL,
total_loan NUMBER(38),
FOREIGN KEY(routing_code) REFERENCES a2_bank(routingcode),
PRIMARY KEY(branch_num, routing_code)
);
@trig.sql
INSERT INTO a2_bankbranch VALUES
( 'ASB', '5', '3 gladstone rd', '123456', '');
INSERT INTO a2_bankbranch VALUES
( 'ASB', '4', '28 stevee rd', '123456', '');
CREATE TABLE a2_loan (
loan_num CHAR(10) PRIMARY KEY,
type VARCHAR(200) NOT NULL,
amount NUMBER(38) NOT NULL,
contract_date DATE NOT NULL,
branch_num VARCHAR(200) NOT NULL,
routing_code VARCHAR(200) NOT NULL,
FOREIGN KEY(routing_code) REFERENCES a2_bank(routing_code),
Foreign KEY(branch_num) REFERENCES a2_bankbranch(branch_num)
);
INSERT INTO a2_loan VALUES
( '323', 'Mortgage', '2000000', TO_DATE('11-03-1994', 'DD-MM-YYYY'), '5', '123456');
INSERT INTO a2_loan VALUES
( '33', 'Car', '2000', TO_DATE('12-08-1994', 'DD-MM-YYYY'), '5', '123456' );
INSERT INTO a2_loan VALUES
( '3243', 'Pesonal', '875', TO_DATE('14-06-1994', 'DD-MM-YYYY'), '5', '123456' );
INSERT INTO a2_loan VALUES
( '6', 'Mortgage', '400500', TO_DATE('11-06-1994', 'DD-MM-YYYY'), '5', '123456' );
我的触发器如下所示,初始插入不起作用,我不知道在WHERE和SET行中放置什么更新和删除 trig.sql如下所示
-- Create a trigger that will update the total loan amount
--that each bank brach may have
CREATE OR REPLACE TRIGGER ttl
AFTER INSERT OR UPDATE OR DELETE OF total_loan ON a2-bankbranch
FOR EACH ROW
BEGIN
IF INSERTING THEN
UPDATE a2_loan
SET total_loan = total_loan + :NEW.amount
WHERE branch_num = :NEW.bank_num;
ELSIF UPDATING THEN
UPDATE a2_loan
SET total_loan = total_loan + amount
WHERE
ELSE --deleting
UPDATE a2_loan
WHERE
END;
非常感谢任何帮助
答案 0 :(得分:0)
首先,标准警告。在现实世界中,你永远不会使用触发器来做这类事情。在现实世界中,您可能不应该首先存储非规范化的总数。如果这样做,您可能希望使用物化视图来维护它。
话虽如此,我希望你想要像
这样的东西CREATE OR REPLACE TRIGGER your_trigger_name
AFTER INSERT, UPDATE, DELETE ON a2_loan
FOR EACH ROW
BEGIN
IF INSERTING
THEN
UPDATE a2_bankbranch
SET total_loan = nvl(total_loan,0) + :new.amount
WHERE routing_code = :new.routing_code
AND branch_num = :new.branch_num;
END IF;
IF UPDATING
THEN
UPDATE a2_bankbranch
SET total_loan = nvl(total_loan,0) - :old.amount
WHERE routing_code = :old.routing_code
AND branch_num = :old.branch_num;
UPDATE a2_bankbranch
SET total_loan = nvl(total_loan,0) + :new.amount
WHERE routing_code = :new.routing_code
AND branch_num = :new.branch_num;
END IF;
IF DELETING
THEN
UPDATE a2_bankbranch
SET total_loan = nvl(total_loan,0) - :old.amount
WHERE routing_code = :old.routing_code
AND branch_num = :old.branch_num;
END IF;
END;