ORACLE SQL%ROWCOUNT在游标提取中不起作用

时间:2017-02-02 15:42:16

标签: oracle plsql

在我的下面的代码中,我无法在游标提取中获取插入的行数。

 ...
row_count NUMBER:= 0;
BEGIN
OPEN object_id_cur(id, c_bool);
            LOOP 
              FETCH object_id_cur INTO l_object_id;
              EXIT WHEN object_id_cur%NOTFOUND;

              INSERT INTO table1( 
                                  id, 
                                  num
                                  )
                     SELECT t2.r_object_id, 
                            t2.num                            
                       FROM table2
                      WHERE t2.r_object_id = l_object_id.r_object_id;
               row_count:= row_count + SQL%ROWCOUNT;
               -- I also tried dbms_output.put_line(SQL%ROWCOUNT); 
            END LOOP;
          CLOSE object_id_cur;
          COMMIT;
          dbms_output.put_line('insert count= ' || row_count || ' rows inserted...');
END;

我获得的结果是:count = rows inserted...计数为空。如果我在光标提取之外移动插入,那么行计数就可以了。对此有合理的解释吗?谢谢!

2 个答案:

答案 0 :(得分:1)

SQL%ROWCOUNT返回执行的最后fetched/processed行数DML。如果由于任何原因在获取1行后DML失败,SQL%ROWCOUNT将仅返回1,到目前为止提取/处理的行数。它不会给你总数。我做了一个简单的PLSQL块并使SQL%ROWCOUNT正常工作。似乎在您的代码中还有其他不起作用的东西。

declare
   num   number := 0;
begin
   for i in 1 .. 10
   loop
      insert into a_table (id)
           values (i);

      num := num + sql%rowcount;
   end loop;

   dbms_output.put_line (num);
end;

答案 1 :(得分:1)

count是保留关键字。使用"count"或其他一些标识符cnt。另外,在增量语句的末尾添加缺少的分号。

declare
  cnt number := 0;
begin
    . . . 
    cnt := cnt + SQL%ROWCOUNT;
    . . .

演示:

SQL> create table t (id int);

Table created.

SQL> declare
  2    cursor c is
  3    select level n from dual connect by level <= 100;  -- produces 100 rows
  4    n int;
  5    cnt number := 0;
  6  begin
  7    open c;
  8    loop
  9      fetch c into n;
 10      exit when c%notfound;
 11      insert into t (id)
 12      select n from dual union all
 13      select n from dual;             -- insert each value twice
 14      cnt := cnt + sql%rowcount;
 15    end loop;
 16    close c;
 17    dbms_output.put_line(cnt);   -- should be 200
 18  end;
 19  /
200               -- correct output

PL/SQL procedure successfully completed.

SQL>

如上所示,SQL%rowcount正常工作。可能是您的下面的选择查询没有产生任何行。

SELECT t2.r_object_id, 
       t2.num                            
FROM table2
WHERE t2.r_object_id = l_object_id.r_object_id;