你想要的是如下的PLSQL塊。
表:
CREATE TABLE temp_table (
job_title VARCHAR2(20),
empname varchar2(30));
--------------------------
CREATE TABLE job (
job_id number,
job_title VARCHAR2(20));
------------------------------
CREATE TABLE emplyee (
empid number,
empname varchar2(30),
job_id number
);
------------------------------
INSERT INTO temp_table VALUES ('Dan', 'Morgan');
INSERT INTO temp_table VALUES ('Helen', 'Lofstrom');
INSERT INTO temp_table VALUES ('Akiko', 'Toyota');
INSERT INTO temp_table VALUES ('Jackie', 'Stough');
INSERT INTO temp_table VALUES ('Richard', 'Foote');
INSERT INTO temp_table VALUES ('Joe', 'Johnson');
INSERT INTO temp_table VALUES ('Clark', 'Urling');
-------------------------
create sequence seq_id start with 1 increment by 1 nocycle;
-----------------
PL SQL塊
declare
dummy integer;
jb_id number;
ep_id number;
job_cntr number:=0;
emp_cntr number:=0;
begin
for rec in (select * from temp_table)
loop
jb_id:= seq_id.nextval*101;
ep_id:= seq_id.nextval;
---Test if row exists before inserting
select count(*)
into dummy
from job jb
where jb.job_title = rec.job_title;
if dummy = 0 then
insert into job(job_id,job_title) values (jb_id,rec.job_title);
else
--dbms_output.put_line('Duplicate record in Job table.!!! Records Exis-'||rec.job_title);
job_cntr:=job_cntr + 1 ;
end if;
---Test if row exists before inserting
select count(*)
into dummy
from emplyee emp
where emp.empname = rec.empname;
if dummy = 0 then
insert into emplyee(empid,empname,job_id) values (ep_id,rec.empname,jb_id);
else
--dbms_output.put_line('Duplicate record in Employee..!!! Records Exis-'||rec.empname);
emp_cntr := emp_cntr + 1;
end if;
end loop;
commit;
dbms_output.put_line('Duplicate record in Job table-'||job_cntr || ' Duplicate record in Employee.' ||emp_cntr);
end;
--
測試:
select * from job;
select * from emplyee;
最簡單的方法可能是剛外連接兩個表,那麼你就會知道哪些行匹配,哪些沒有。 –