2016-09-15 33 views
0

使用PL SQL过程从一个临时表中插入不同的表 我该如何检查,如果一个记录被重复使用if语句PLSQL - 光标,看有没有记录已经存在

  1. 如果犯规存在,然后插入
  2. 如果确实存在,则显示一个消息(DBMS_OUTPUT.PUT_LINE)重复和继续在环与其他记录

临时表:

create table temp_table 
(job title varchar2(20) 
,empname varchar2(30)); 

我有一个工作表job_idjob_title 我有一个雇员表empidempnamejobid

+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块

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; 
+0

谢谢你,很好的帮助!.....如果我们有2个'丹'的记录,'摩根'有什么方法可以记录这个?以显示这些是重复的 –

+0

如果.....然后引发'异常名称',我们可以引发异常并处理它 – XING

+0

? –