数据库 中有张表test
原始的数据为:
id1   id2
1001  10
1002  10
1003  10
1004  10
2001  10
2002  10
 
另外有张代码表,映射test表中id1字段的后两位与id2的关系
id1   id2
01    1001
02    1002
03    1003
04    1004现在想更新test表,就是在插入的时候判断id1这个字段的后两位的值,对应代码表中,将id2字段的值进行更新
比如现在有一条原始数据为3001 10要插入到test表中,现在想通过触发器变成3001 1001插入到test中请问这个触发器如何实现?

解决方案 »

  1.   


    SQL> create table test(id1 varchar2(10),id2 varchar2(10));Table createdSQL> insert into test values('1001','10');1 row insertedSQL> insert into test values('1002','10');1 row insertedSQL> insert into test values('1003','10');1 row insertedSQL> insert into test values('1004','10');1 row insertedSQL> insert into test values('2001','10');1 row insertedSQL> insert into test values('2002','10');1 row insertedSQL> commit;Commit completeSQL> create table test_code(id1 varchar2(10),id2 varchar2(10));Table createdSQL> insert into test_code values('01','1001');1 row insertedSQL> insert into test_code values('02','1002');1 row insertedSQL> insert into test_code values('03','1003');1 row insertedSQL> insert into test_code values('04','1004');1 row insertedSQL> commit;Commit complete
    SQL> create or replace trigger trigger_test_code
      2  before insert on test
      3  for each row
      4  declare
      5  v_id2 varchar2(10);
      6  begin
      7    select id2 into v_id2 from test_code where id1=substr(:new.id1,-2);
      8    if v_id2 is not null then
      9       :new.id2:=v_id2;
     10    end if;
     11  end;
     12  /

    Trigger createdSQL> select * from test;ID1        ID2
    ---------- ----------
    1001       10
    1002       10
    1003       10
    1004       10
    2001       10
    2002       106 rows selectedSQL> select * from test_code;ID1        ID2
    ---------- ----------
    01         1001
    02         1002
    03         1003
    04         1004SQL> insert into test values('3001','10');1 row insertedSQL> select * from test;ID1        ID2
    ---------- ----------
    1001       10
    1002       10
    1003       10
    1004       10
    2001       10
    2002       10
    3001       10017 rows selectedSQL> 
      

  2.   

    本帖最后由 wildwave 于 2010-05-12 14:58:15 编辑