使用自联接将批量数据插入到oracle表中

时间:2012-02-13 14:46:16

标签: sql oracle plsql

我有一个名为p_relations的表,其中包含4列employeenameaccessmanager_namecomments,我可以从表中获取这些详细信息{ {1}} p_employeesemp_idname

例如在manager_id表中我有这些数据:

p_employees

现在在1001 kiran 2001 2001 rahul 3001 表中我必须插入像这样的数据

p_relations

实际上我们必须插入批量数据。你能告诉我这个程序或问题。

我开发了简单的程序,但它不起作用:

kiran  1   rahul

请帮我解决这个问题

3 个答案:

答案 0 :(得分:2)

听起来你可以使用分层查询,它使用CONNECT BY PRIOR语法,而不是PL / SQL循环,只需使用简单的INSERT INTO SELECT...

    INSERT INTO p_relations
    SELECT name, 1, (SELECT name FROM p_employees m WHERE e.manager_id = m.emp_id)
    FROM p_employees e
    START WITH manager_id IS NULL -- Specify how to identify your top manager, the big boss.
    CONNECT BY emp_id = PRIOR manager_id;

答案 1 :(得分:0)

可能并非所有员工都有经理。 你可以用左连接来做到这一点:

INSERT into p_relations
SELECT a.name, 1, b.name as manager_name 
FROM WKS_CONT.SIBER_EMPLOYEES a
    left join WKS_CONT.SIBER_EMPLOYEES b on (b.emp_id=a.manager_id);

可以通过这种方式改进您的程序:

DECLARE
e_name VARCHAR2(20);
m_name VARCHAR2(20);
manager_id VARCHAR2(20);
 CURSOR c_lecturer IS
   SELECT name,manager_id FROM p_employees;
BEGIN 
   OPEN c_lecturer; 
   LOOP 
       FETCH c_lecturer 
       INTO e_name, manager_id; 

       BEGIN
         SELECT name INTO manager_name 
         FROM WKS_CONT.SIBER_EMPLOYEES WHERE emp_id=manager_id;
       EXCEPTION when no_rows_found then manager_name:=null;
       END;

       INSERT INTO p_relations  VALUES(e_name, 1, manager_name);

EXIT WHEN c_lecturer%NOTFOUND;
 END LOOP;
CLOSE c_lecturer;
END;

答案 2 :(得分:0)

如果可能的话,使用bulk collect通常会更有效率。它看起来有点可怕,但值得努力去理解;一开始它做的DML少了

declare

   cursor c_lecturer is
    select e.name, 1, m.name
      from p_employees e
      left outer join wks_cont.siber_employees m
        on e.emp_id = m.manager_id
           ;

   t__lecturer is table of c_lecturer%rowtype index by binary_integer;
   t_lecturer t__lecturer;

begin

   open c_lecturer;
   loop

      fetch c_lecturer bulk collect 
       into t_lecturer limit 1000;

      exit when t_lecturer.count = 0;

      forall i in t_lecturer.first .. t_lecturer.last loop
         insert into p_relations(e_name, access, manager_name)
         values t_lecturer(i)
                ;

      commit;

   end loop;
   close c_lecturer;

end;
/

当然,更有效的是一个简单的插入:

insert into p_relations(e_name, access, manager_name)
select e.name, 1, m.name
  from p_employees e
  left outer join wks_cont.siber_employees m
    on e.emp_id = m.manager_id
       ;