17,377
社区成员
发帖
与我相关
我的任务
分享
create or replace trigger tb1_operate
before insert on tb1
for each row
declare
v_weight number;
v_count number;
begin
select max(权重) into v_weight from tb1 where 部门 = :new.部门;
select count(*) into v_count from tb1 where 部门 = :new.部门;
if v_count = 0 then
insert into tb2 (部门, 姓名) values (:new.部门, :new.姓名);
elsif v_weight < :new.权重 then
update tb2 set 姓名 = :new.姓名 where 部门 = :new.部门;
end if;
end;
--沒有錯噢,是不是你還有其他限制,給你看結果,不過我這是繁體
SQL> insert into tb1 values('部門A',35,'王五');
已建立 1 個資料列.
SQL> insert into tb1 values('部門C',10,'李明');
已建立 1 個資料列.
SQL> insert into tb1 values('部門C',20,'王強');
已建立 1 個資料列.
SQL> insert into tb1 values('部門D',20,'劉八');
已建立 1 個資料列.
SQL> commit;
確認完成.
SQL> select * from tb1;
部門 權重 姓名
-------------------- ---------- --------------------
部門A 35 王五
部門C 10 李明
部門C 20 王強
部門D 20 劉八
SQL> select * from tb2;
部門 姓名
-------------------- --------------------
部門A 王五
部門C 王強
部門D 劉八
--又是体力活,呵呵
create or replace trigger tb1_insupd
before insert
on tb1
for each row
declare
v_cou int := 0;
v_cou1 int := 0;
v_power int := 0;
begin
select count(1) into v_cou from tb2 where 部门=:new.部门;
select count(1) into v_cou1 from tb1 where 部门=:new.部门;
if v_cou1<>0 then
select max(权重) into v_power from tb1 where 部门=:new.部门 group by 部门;
end if;
if v_cou<>0 and v_power<:new.权重 then
update tb2 set 姓名=:new.姓名 where tb2.部门=:new.部门;
elsif v_cou=0 then
insert into tb2 values(:new.部门,:new.姓名);
end if;
end;
/