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

时间:2012-08-12 11:43:27

标签: sql oracle cursor

我有2个表格,studentstudLoad都有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;

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

1 个答案:

答案 0 :(得分:15)

这是一种非常低效的方法。您可以使用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)

确保您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;
/