oracle 当光标数据未找到时如何插入日期

vfwfrxfs  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(92)

我有一个游标C_RegstCursor和当C_RegstCursor %notfound然后我想插入psome记录表。

FETCH C_RegstCursor INTO
       f--fetc values to variable                 
     v_reg_comment;

 WHEN C_RegstCursor %notfound then

将数据插入表..和一组要插入多个表的语句
如果我尝试运行光标它给出了一个错误符号“当”遇到时,以下之一是预期的:
(开始case declare end exit for后藤if loop mod NULL pragma raise return select update whil)
如果没有找到,我该怎么写?插入后我应该退出吗?

8hhllhi2

8hhllhi21#

要完成您想要的任务,一个选择是使用一个局部变量,它计算游标返回的行数。如果没有行,则执行插入。
样本数据:

SQL> select * From dept order by deptno;

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON

过程;显然,没有deptno = 99,因此游标不会返回任何内容。

SQL> declare
  2    cursor c1 is select deptno, dname, loc
  3      from dept
  4      where deptno = 99;
  5    c1r c1%rowtype;
  6    l_cnt number := 0;
  7  begin
  8    open c1;
  9    loop
 10      fetch c1 into c1r;
 11      exit when c1%notfound;
 12      l_cnt := l_cnt + 1;
 13
 14      -- do something within the loop, if there are any rows returned by cursor
 15    end loop;
 16    close c1;
 17
 18    if l_cnt = 0 then
 19       -- cursor didn't return anything
 20       insert into dept (deptno, dname, loc)
 21         values (99, 'Test', 'Test');
 22    end if;
 23  end;
 24  /

PL/SQL procedure successfully completed.

测试结果:

SQL> select * from dept order by deptno;

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON
        99 Test           Test             --> newly added row

SQL>

相关问题