当前位置: 代码迷 >> Oracle开发 >> 在数据库中怎么实现? 希望能给出代码
  详细解决方案

在数据库中怎么实现? 希望能给出代码

热度:20   发布时间:2016-04-24 07:21:32.0
在数据库中如何实现? 希望能给出代码
比如表A数据如下:
1 张三 20110913
2 张三 20110914
3 李四 20110913
4 李四 20110914
5 王五 20110913
6 马六 20110914

B表:(相当于A表的索引,每个人只会有1条记录,不能重复;而A表中的数据是每个人可以有多条,可以重复的。)
1 张三 20110914
2 李四 20110914
3 王五 20110913
4 马六 20110914

---------如果,我现在往A表里面插入:

7 张三 20110915

我希望这个时间也能更新到B表中。也就是每次只要往A表中插入数据,数据库会自动在B表中找到相对应的人,更改他的时间







------解决方案--------------------
触发器
------解决方案--------------------
SQL code
create table testa(    sname    varchar2(30),    stime    varchar2(20));create table testb as select * from testa;create or replace trigger tri_testb  after insert on testa    for each rowdeclare  -- local variables herebegin    if inserting then        merge into testb a        using (select :new.sname as sname, :new.stime as stime from dual) b           on (a.sname = b.sname)         when matched then        update set a.stime = b.stime         when not matched then        insert (a.sname, a.stime)        values (b.sname, b.stime);    end if;end tri_testb;/select * from testb;insert into testa values('张三', '20110912');insert into testa values('张三', '20110913');insert into testa values('张三', '20110914');insert into testa values('李四', '20110912');insert into testa values('张三', '20110913');commit;select * from testb;insert into testa values('张三', '20110915');commit;select * from testb;
------解决方案--------------------
建立一个针对A表insert的触发器,如果表为a、b,字段为name,time
CREATE OR REPLACE TRIGGER TR_AUTO
 after INSERT ON 表A
 FOR EACH ROW
DECLARE
 NEXTID NUMBER;
BEGIN
SELECT SEQ_ADV_IDX.NEXTVAL INTO NEXTID FROM DUAL;
update b set b.time= :NEW.time where b.name=:NEW.name
END;

------解决方案--------------------
SQL code
楼上都已经些出来了,我就不再写了这个其实就是触发器的基本功能啊:A表插入后 (after insert)触发触发器,触发器的功能有两步:1,查询B表(查看B表中是否已经有该数据了);2,根据查询结果作更新或插入操作(1的返回结果为true,则更新B表;否则插入B表)ps:A表中新插入的数据可以用(:NEW.xxxx)取得
  相关解决方案