PL / SQL中的UPDATE影响的行数

我有一个PL / SQL函数(在Oracle 10g上运行),其中我更新了一些行。 有没有办法找出有多less行被更新影响? 当手动执行查询时,会告诉我有多less行受到影响,我想在PL / SQL中获取该数字。

你使用sql%rowcountvariables。 您需要在声明之后直接调用它来查找受影响的行数。 例如:

declare i number; begin update employees set status = 'fired' where name like '%Bloggs'; i := sql%rowcount; end; 

对于那些希望得到明确命令结果的人,解决scheme可能是:

 begin DBMS_OUTPUT.PUT_LINE(TO_Char(SQL%ROWCOUNT)||' rows affected.'); end; 

基本问题是SQL%ROWCOUNT是PL / SQLvariables(或函数),不能直接从SQL命令中访问。 通过使用非名称PL / SQL块,可以实现这一点。

…如果有人有一个解决scheme在SELECT命令中使用它,我会感兴趣。

或者, SQL%ROWCOUNT你可以在程序中使用这个,而不需要声明一个variables

SQL%ROWCOUNT也可以在不被分配的情况下使用(至less从Oracle 11g )。

只要在当前块内没有执行任何操作(更新,删除或插入), SQL%ROWCOUNT就设置为空。 然后它保持受最后一个DML操作影响的行数:

说我们有客户表

 create table client ( val_cli integer ,status varchar2(10) ) / 

我们会这样testing它:

 begin dbms_output.put_line('Value when entering the block:'||sql%rowcount); insert into client select 1, 'void' from dual union all select 4, 'void' from dual union all select 1, 'void' from dual union all select 6, 'void' from dual union all select 10, 'void' from dual; dbms_output.put_line('Number of lines affected by previous DML operation:'||sql%rowcount); for val in 1..10 loop update client set status = 'updated' where val_cli = val; if sql%rowcount = 0 then dbms_output.put_line('no client with '||val||' val_cli.'); elsif sql%rowcount = 1 then dbms_output.put_line(sql%rowcount||' client updated for '||val); else -- >1 dbms_output.put_line(sql%rowcount||' clients updated for '||val); end if; end loop; end; 

导致:

 Value when entering the block: Number of lines affected by previous DML operation:5 2 clients updated for 1 no client with 2 val_cli. no client with 3 val_cli. 1 client updated for 4 no client with 5 val_cli. 1 client updated for 6 no client with 7 val_cli. no client with 8 val_cli. no client with 9 val_cli. 1 client updated for 10 

使用Count(*)分析函数OVER PARTITION BY NULL这将计算总行数