使用pl sql过程从临时表插入到单独的表中 如何使用if语句检查记录是否重复
临时表:
create table temp_table
(job title varchar2(20)
,empname varchar2(30));
我有一张job_id
的工作表,job_title
我有一张包含empid
,empname
,jobid
答案 0 :(得分:0)
您想要的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 Block
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;