Prevent deleting more than one record at a time with a trigger in Oracle

0

I need to implement something similar to what SQLServer does but in Oracle:

CODE: SQLSERVER

CREATE TRIGGER TR_ImpideBorradoMultiple 
   ON MiTabla AFTER DELETE
AS
BEGIN
   IF(SELECT COUNT(*) FROM Deleted) > 1
   Begin
      raiserror('Prohibido eliminar mas de un registro a la vez', 16, 1)
      rollback transaction
   End
END

From what I have seen, in Oracle there are the variables: Old and: New, which are of type% rowtype so they only refer to the affected row, instead in SQLServer, Deleted refers to the set of affected rows .. I must conclude then that you can not do this in Oracle ???

    
asked by Rodrigo Valdivia 21.07.2017 в 16:43
source

3 answers

0

After reviewing the Oracle documentation, you can effectively only access the affected record and never all of them. Therefore, the following solution occurs to me: Use a table (can be temporary) that counts the eliminations in a trigger for each row of type before (before); then with a trigger of after-type order (after), consult what is posted:

Create or Replace Trigger Tr_CalculaEliminacionMultiple
   Before delete
   On Empleados
   for each row  /*este trigger se ejecuta por cada fila afectada*/
Begin
   Update EmpleCuentaDeleteRows /*tabla para contabilizar filas afectadas*/
   Set NumFilas = NumFilas + 1;
end;


/*Trigger se dispara despues de la ejecución de la orden.*/
Create or Replace Trigger Tr_EvitaEliminacionMultiple
   after delete
   On Empleados
Declare
   Filas number;
Begin

   Select NumFilas into Filas
   from EmpleCuentaDeleteRows; /*tabla para contabilizar filas afectadas.*/

   if Filas > 1 Then
      raise_application_error(-20001,'No se puede!!!');
   else
      update EmpleCuentaDeleteRows
      set NumFilas = 0;
   end if;
end;

I think the performance will be affected, compared to SQL-SERVER, but I do not see another alternative.

    
answered by 26.07.2017 / 23:32
source
0

The Oracle documentation is quite concise about it:

  

Because the trigger uses the FOR EACH ROW clause, it might be executed   multiple times, such as when updating or deleting multiple rows. You   might omit this clause if you just want to record the fact that the   operation occurred, but not examine the data for each row.

If the trigger uses the FOR EACH ROW will be executed for each row, you can omit this clause, for example to register that a DELETE occurred but you will not be able to examine the data involved, therefore you will not be able to determine if it is a delete of multiple registers to trigger an error and prevent the operation.

    
answered by 21.07.2017 в 21:39
-1

As you mention Oracle has the objects: new and: old, these only affect the record that is being modified, you could better describe what you want to do and what the problem is. If you attach the code it would be very helpful.

    
answered by 21.07.2017 в 19:47