Answers:
您使用sql%rowcount
变量。
您需要在需要查找受影响的行数的语句之后直接调用它。
例如:
set serveroutput ON;
DECLARE
i NUMBER;
BEGIN
UPDATE employees
SET status = 'fired'
WHERE name LIKE '%Bloggs';
i := SQL%rowcount;
--note that assignment has to precede COMMIT
COMMIT;
dbms_output.Put_line(i);
END;
INSERT INTO
.. 的过程,COMMIT
并且在插入后也有相同的过程,我有UPDATE SET WHERE EXISTS..COMMIT
,但是我i := SQL%rowcount;
将返回所有行,而不是仅更新的行。可能是什么?
或者,SQL%ROWCOUNT
您可以在过程中使用它,而无需声明变量
SQL%ROWCOUNT
也可以不分配使用(至少从Oracle 11g中)。
只要在当前块内未执行任何操作(更新,删除或插入),就将SQL%ROWCOUNT
其设置为null。然后,它保持受上一个DML操作影响的行数:
说我们有表CLIENT
create table client (
val_cli integer
,status varchar2(10)
)
/
我们将以这种方式进行测试:
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
请试试这个..
create table client (
val_cli integer
,status varchar2(10)
);
---------------------
begin
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;
end;
---------------------
select * from client;
---------------------
declare
counter integer := 0;
begin
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.');
else
dbms_output.put_line(sql%rowcount||' client updated for '||val);
counter := counter + sql%rowcount;
end if;
end loop;
dbms_output.put_line('Number of total lines affected update operation: '||counter);
end;
---------------------
select * from client;
--------------------------------------------------------
结果将如下所示:
2个客户端已更新为1个
客户端,没有2个val_cli。
没有3 val_cli的客户端。
1个客户端已更新为4个
客户端,没有5个val_cli。
1个客户端已更新为6个
客户端,没有7个val_cli。
没有客户端使用8 val_cli。
没有客户端使用9 val_cli。
1个客户端已更新10个
,影响更新操作的总行数:5
使用Count(*)分析函数OVER PARTITION BY NULL这将计算总行数