現有一張老師學生表(tb_tea_cou),由於業務需要,需把老師學生表tb_tea_stu拆分成兩張表(tb_tea、tb_cou),並把記錄insert到這兩張子表中(tb_tea、tb_cou為關聯的兩張表)。
表結構如下:
tb_tea_cou(
id, //pk
name, //任課老師
zc, //職稱
course //課程
),
老師表:
tb_tea(
tid, //pk
tname, //任課老師
zc //職稱
),
課程表:
tb_cou(
cid, //pk
course, //課程
tea_id //fk,tb_tea id
)
插入資料
INSERT INTO tb_tea_cou (ID, name, zc, course) VALUES (hibernate_seq.nextval, '張三', '教師', '語文'); INSERT INTO tb_tea_cou (ID, name, zc, course) VALUES (hibernate_seq.nextval, '李四', '教師', '數學'); INSERT INTO tb_tea_cou (ID, name, zc, course) VALUES (hibernate_seq.nextval, '王五', '教師', '英語'); INSERT INTO tb_tea_cou (ID, name, zc, course) VALUES (hibernate_seq.nextval, '老劉', '教師', '歷史'); INSERT INTO tb_tea_cou (ID, name, zc, course) VALUES (hibernate_seq.nextval, '小王', '教師', '政治'); INSERT INTO tb_tea_cou (ID, name, zc, course) VALUES (hibernate_seq.nextval, '杜甫', '教師', '生物'); INSERT INTO tb_tea_cou (ID, name, zc, course) VALUES (hibernate_seq.nextval, '李白', '教師', '化學'); INSERT INTO tb_tea_cou (ID, name, zc, course) VALUES (hibernate_seq.nextval, '韓愈', '教師', '物理'); select * from tb_tea_cou;
思路,使用儲存過程,插入tb_tea表之後,select max(tid) from tb_tea; 得到剛剛插入的序列的最大值,在後面將這個值插入tb_cou表中。
--建立儲存過程 SET serveroutput ON; CREATE OR REPLACE PROCEDURE proce_insert_tab(error_msg OUT VARCHAR2) IS v_id NUMBER(9, 2); BEGIN FOR cur IN (select * FROM tb_tea_cou) LOOP SELECT hibernate_seq.nextval INTO v_id FROM dual; INSERT INTO tb_tea(tid, tname, zc) VALUES ( v_id, cur.name, cur.zc); INSERT INTO tb_cou(cid, course, tea_id) VALUES ( hibernate_seq.nextval, cur.course, v_id); COMMIT; error_msg:='新增成功'; END LOOP; EXCEPTION WHEN OTHERS THEN ROLLBACK; error_msg:='新增失敗'; RAISE_APPLICATION_ERROR(-20010, 'ERROR:插入資料有誤!'); END; / --呼叫儲存過程 var error_msg VARCHAR2(200); exec proce_insert_tab(:error_msg); SELECT * FROM tb_tea; SELECT * FROM tb_cou; SELECT t.tid, t.tname, t.zc, c.course FROM tb_tea t, tb_cou c WHERE t.tid=c.tea_id delete from tb_tea; delete from tb_cou;