使用oracle中的游标INSERT和UPDATE记录

z22*_*z22 2 sql oracle cursor

我有2个表student- studLoad两个都有2个字段studIDstudName.我想将student表中的数据加载到stuLoad表中.如果studLoad表中已存在数据,则应更新它,否则应插入.以下是我的代码:

    create or replace procedure studentLoad is
v_id student.studID%type;
v_name student.studName%type;
v_sn studLoad.studName%type;
cursor cur_load is
select * from student;


begin
  open cur_load;
  loop
   fetch cur_load into v_id,v_name;

   exit when cur_load%notfound;
   select studName into v_sn from studLoad where studID = v_id;
   if(v_sn!= v_name) then
      update studLoad set studName= v_name where studID= v_id;
   else
      insert into studLoad values(v_id,v_name);
   dbms_output.put_line(v_id || ' ' || v_name);
   end if;
  end loop;
      close cur_load;
end;
Run Code Online (Sandbox Code Playgroud)

它不起作用.studLoad表中的行是noT更新.我该如何解决这个问题?在SQL server中我们IF EXISTS(select...from stuLoad..)用来检查表中是否存在记录,有没有办法在Oracle中做同样的事情?如果是,那么请让我知道同样的事情.

Ben*_*Ben 16

这是一种非常低效的方法.您可以使用该merge语句,然后不需要游标,循环或(如果没有)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)
Run Code Online (Sandbox Code Playgroud)

确保commit完成后,为了能够在数据库中看到这一点.


要真正回答你的问题,我会做如下的事情.这样做的好处是可以在SQL中完成大部分工作,并且只能基于rowid(表中的唯一地址)进行更新.

它声明了一个类型,您可以批量放置数据,一次放置10,000行.然后单独处理这些行.

但是,正如我所说,这将不如效率高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;
/
Run Code Online (Sandbox Code Playgroud)