如何更新列?

时间:2016-05-22 16:13:59

标签: sql oracle plsql triggers

我创建了以下表格:

create table AandB (
        code              varchar(9),
        total             number,
        CONSTRAINT pk_code PRIMARY KEY (code)
);

create table A (
        codeA              varchar(9),
        numberA              number,
        CONSTRAINT pk_codeA PRIMARY KEY (codeA)
);

create table B (
        codeB              varchar(9),
        numberB            number,
        CONSTRAINT pk_codeB PRIMARY KEY (codeB)

);

我插入了以下数据:

insert into AandB(code) values('0x1');
insert into AandB(code) values('0x2');
insert into AandB(code) values('0x3');

insert into A(codeA, numberA) values('0x1',5);
insert into A(codeA, numberA) values('0x2',6);
insert into A(codeA, numberA) values('0x3',1);

insert into B(codeB, numberB) values('0x1',8);
insert into B(codeB, numberB) values('0x2',10);
insert into B(codeB, numberB) values('0x3',12);

问题是:如何使用触发器更新表“AandB”?

我使用以下查询添加两个表:

UPDATE AandB ab
SET ab.total = (SELECT a.numberA + b.numberB
                FROM A
                INNER JOIN B
                 ON(a.codeA = b.codeB)
                WHERE a.codeA = ab.code)

现在,0X1 = 13.但如果我更新表A:

update A set numberA=10 where codeA='0x1';

现在,0X1应该是0x1 = 18

2 个答案:

答案 0 :(得分:1)

改为创建视图,始终是最新的!

create view AandB (code, total) as
SELECT a.code, a.numberA + b.numberB
FROM A
INNER JOIN B ON (a.codeA = b.codeB)

答案 1 :(得分:0)

你可以创建一个trigger,它将在列"数字"的每次更新时执行。两个表格" A"和" B"。触发器的主体可以与更新语句相同:

UPDATE AandB ab
SET ab.total = (SELECT a.numberA + b.numberB
                FROM A
                INNER JOIN B
                 ON(a.codeA = b.codeB)
                WHERE a.codeA = ab.code)

为了获得更好的性能,您可以添加" WHERE"条款如下:

(对于表A的触发器)

WHERE ab.code = :NEW.numberA

(对于表B的触发器)

WHERE ab.code = :NEW.numberB