INSERT and UPDATE a record using cursors in oracle

前端 未结 1 784
日久生厌
日久生厌 2020-12-29 16:48

I have 2 tables- student and studLoad both having 2 fields studID and studName. I want to load data from student

相关标签:
1条回答
  • 2020-12-29 17:24

    This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

    MERGE INTO studLoad l
    USING ( SELECT studId, studName FROM student ) s
    ON (l.studId = s.studId)
    WHEN MATCHED THEN
      UPDATE SET l.studName = s.studName
       WHERE l.studName != s.studName
    WHEN NOT MATCHED THEN 
    INSERT (l.studID, l.studName)
    VALUES (s.studId, s.studName)
    

    Make sure you commit, once completed, in order to be able to see this in the database.


    To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

    It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

    However, as I say this will not be as efficient as merge.

    declare
    
       cursor c_data is
        select b.rowid as rid, a.studId, a.studName
          from student a
          left outer join studLoad b
            on a.studId = b.studId
           and a.studName <> b.studName
               ;
    
       type t__data is table of c_data%rowtype index by binary_integer;
       t_data t__data;
    
    begin
    
       open c_data;
       loop
          fetch c_data bulk collect into t_data limit 10000;
    
          exit when t_data.count = 0;
    
          for idx in t_data.first .. t_data.last loop
             if t_data(idx).rid is null then
                insert into studLoad (studId, studName)
                values (t_data(idx).studId, t_data(idx).studName);
             else
                update studLoad
                   set studName = t_data(idx).studName
                 where rowid = t_data(idx).rid
                       ;
             end if;
          end loop;
    
       end loop;
       close c_data;
    
    end;
    /
    
    0 讨论(0)
提交回复
热议问题