sql >> Base de Datos >  >> RDS >> Oracle

INSERTAR y ACTUALIZAR un registro usando cursores en Oracle

Esta es una forma muy ineficiente de hacerlo. Puedes usar merge declaración y luego no hay necesidad de cursores, bucles o (si puede prescindir) 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)

Asegúrate de commit , una vez completado, para poder verlo en la base de datos.

Para responder realmente a su pregunta, lo haría de la siguiente manera. Esto tiene la ventaja de hacer la mayor parte del trabajo en SQL y solo se actualiza según el ID de fila, una dirección única en la tabla.

Declara un tipo, en el que coloca los datos de forma masiva, 10 000 filas a la vez. Luego procesa estas filas individualmente.

Sin embargo, como digo, esto no será tan eficiente como 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;
/