Número de filas afectadas por una ACTUALIZACIÓN en PL / SQL


Tengo una función PL/SQL (ejecutándose en Oracle 10g) en la que actualizo algunas filas. ¿Hay alguna forma de averiguar cuántas filas se vieron afectadas por la ACTUALIZACIÓN? Al ejecutar la consulta manualmente me dice cuántas filas se vieron afectadas, quiero obtener ese número en PL / SQL.

Author: linuxbuild, 2009-05-14

6 answers

Se utiliza la variable sql%rowcount.

Debe llamarlo directamente después de la instrucción para la que necesita encontrar el recuento de filas afectado.

Por ejemplo:

DECLARE
    i number;
BEGIN
    UPDATE employees
    SET status = 'fired'
    WHERE name like '%Bloggs';
    i := sql%rowcount;
END;
 209
Author: Clive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-08 22:22:32

Para aquellos que quieren los resultados de un comando simple, la solución podría ser:

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

El problema básico es que SQL%ROWCOUNT es una variable (o función) PL/SQL, y no se puede acceder directamente desde un comando SQL. Mediante el uso de un bloque PL/SQL sin nombre, esto se puede lograr.

... Si alguien tiene una solución para usarlo en un Comando SELECT, me interesaría.

 20
Author: CLS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-03 07:55:20

Alternativamente, SQL%ROWCOUNT puede usar esto dentro del procedimiento sin necesidad de declarar una variable

 6
Author: Ali H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-06 14:03:38

SQL%ROWCOUNT también se puede usar sin ser asignado (al menos desde Oracle 11g ).

Mientras no se haya realizado ninguna operación (actualizaciones, eliminaciones o inserciones) dentro del bloque actual, SQL%ROWCOUNT se establece en null. Luego se queda con el número de línea afectada por la última operación DML:

digamos que tenemos CLIENTE de mesa

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

Lo probaríamos de esta manera:

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;

Como resultado:

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
 1
Author: J. Chomel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-15 15:18:28

Por favor, pruebe este..


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;

--------------------------------------------------------

El resultado será el siguiente:


2 cliente actualizado para 1
ningún cliente con 2 val_cli.
ningún cliente con 3 val_cli.
1 cliente actualizado para 4
ningún cliente con 5 val_cli.
1 cliente actualizado para 6
ningún cliente con 7 val_cli.
ningún cliente con 8 val_cli.
ningún cliente con 9 val_cli.
1 cliente actualizado para 10
Número total de líneas afectadas operación de actualización: 5


 -1
Author: Arun Sundriyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-23 16:17:18

Utilice la función analítica Count (*) SOBRE LA PARTICIÓN POR NULL Esto contará el número total de filas

 -3
Author: guest,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-03 00:50:55