How to get number of rows affected by a statement when inside that statement's trigger - oracle

I have a statement level trigger that fires whenever INSERT UPDATE or DELETE operations are performed on a table (called customers). I want to display a message (to DBMS_OUTPUT) containing the number of rows that were inserted/updated/deleted.
I just want one message for each triggering statement, eg
'4 rows were inserted into customers table'.
How can I access the number of rows that are affected by the triggering statement from INSIDE the trigger declaration, ie XXX in the code below:
CREATE OR REPLACE TRIGGER customer_changes_trigger_2
AFTER INSERT OR UPDATE OR DELETE ON customers
DECLARE
v_operation VARCHAR(10);
v_number_rows NUMBER;
BEGIN
v_number := XXX;
IF INSERTING THEN
v_operation := 'inserted';
END IF;
IF UPDATING THEN
v_operation := 'updated';
END IF;
IF DELETING THEN
v_operation := 'deleted';
END IF;
DBMS_OUTPUT.PUT_LINE
(v_number_rows|| ' rows were ' || v_operation || ' from customers.');
END;
Can't find anything in the documentation, any help appreciated!

One way is to use a global variable to track the number of rows as there is no other way to get the row count from a statement level trigger. You would then need three triggers... one statement level to initialise the variable before the statement is run, one row level to add one to the variable for each row, one statement level to use the row count however you wish. First, set up the variable and a few procedures to help it:
create or replace package PKG_ROWCOUNT is
NUMROWS number;
procedure INIT_ROWCOUNT;
procedure ADD_ONE;
function GET_ROWCOUNT
return number;
end PKG_ROWCOUNT;
/
create or replace package body PKG_ROWCOUNT as
procedure INIT_ROWCOUNT is
begin
NUMROWS := 0;
end;
procedure ADD_ONE is
begin
NUMROWS := Nvl(NUMROWS, 0) + 1;
end;
function GET_ROWCOUNT
return number is
begin
return NUMROWS;
end;
end PKG_ROWCOUNT;
/
The first trigger to initialise the variable:
create or replace trigger CUSTOMER_CHANGES_TRIGGER_1
before insert or update or delete
on CUSTOMERS
begin
PKG_ROWCOUNT.INIT_ROWCOUNT;
end;
The second to update per row:
create or replace trigger CUSTOMER_CHANGES_TRIGGER_2
after insert or update or delete
on CUSTOMERS
for each row
begin
PKG_ROWCOUNT.ADD_ONE;
end;
/
The third to display the total:
create or replace trigger CUSTOMER_CHANGES_TRIGGER_3
after insert or update or delete
on CUSTOMERS
begin
Dbms_output.
PUT_LINE(PKG_ROWCOUNT.GET_ROWCOUNT || ' rows were affected.');
end;

I'm not 100$ sure if it's available inside AFTER trigger body, but you can try examining sql%rowcount

Related

how to update a column using oracle trigger

CREATE OR REPLACE TRIGGER demands
AFTER INSERT ON demand
FOR EACH ROW
DECLARE
MRPs number;
BEGIN
SET demand.MRP=10;
dbms_output.put_line('Salary difference: ' || :NEW. PRODUCT_NAME);
END;
I want to set the mrp =value x (which is not same every time for solving the issue we are supposing it to be 10 ) after the row is inserted
Use :NEW.MRP := 10 in a BEFORE INSERT trigger (if you use AFTER INSERT then the value will already have been inserted and you cannot change it).
CREATE OR REPLACE TRIGGER demands
BEFORE INSERT ON demand
FOR EACH ROW
BEGIN
:NEW.MRP := 10;
END;
/
db<>fiddle here

how to pass a whole row as record to a function in oracle triggers

I create a oracle package with function where in the input is a whole row and the output is varray. i want to use this package function to apply on all the rows of a table using trigger as soon as new record is inserted. I tried like this but the output is bad bind variable
create or replace trigger custdata_caferrors
before insert or update on customer_data
referencing new as n old as o
for each row
declare
v_remarks varchar(500) :=' ';
t_remarks caf_errors :=caf_errors();
rec customer_data%rowtype;
begin
-- rec = :n;
t_remarks := CUSTDATA_VERIFY.VERIFY_TERMSTATUS(:n);
for x in 1..t_remarks.count
loop
v_remarks :=v_remarks||' , '||t_remarks(x);
end loop;
:n.record_status1 :=v_remarks;
end;
/
Unfortunately there is no way to reference a whole new row in a trigger. I agree it would be neat if this were possible, but alas.
So you will have to explicitly populate your rec variable with the column values you require and pass that to your function, like this
create or replace trigger custdata_caferrors
before insert or update on customer_data
referencing new as n old as o
for each row
declare
v_remarks varchar(500) :=' ';
t_remarks caf_errors :=caf_errors();
rec customer_data%rowtype;
begin
rec.id := :n.id;
rec.col1 := :n.col1;
-- etc
t_remarks := CUSTDATA_VERIFY.VERIFY_TERMSTATUS(rec);
for x in 1..t_remarks.count
loop
v_remarks :=v_remarks||' , '||t_remarks(x);
end loop;
:n.record_status1 :=v_remarks;
end;
/
Do you really need to pass the whole row to CUSTDATA_VERIFY.VERIFY_TERMSTATUS()? If not you might get away with populating just the columns the function actually uses (although that does contravene the Law of Demeter).

TRIGGERS insert same table - PLSQL

Here's my problem:
I have to transform something like this
Into this in the same table
I've tried triggers but I have mutating issues, I have no control about the inserts but I need to do that for every row with value larger than 1.
Any sugestions?
Depending on the number of transactions you're looking at, it may not be a feasible approach, but you might try something along these lines:
CREATE OR REPLACE TRIGGER {TRIGGER NAME}
BEFORE INSERT ON {TABLE HERE}
FOR EACH ROW
DECLARE
l_val INTEGER;
BEGIN
l_val := :new.value - 1;
IF l_val > 0 THEN
:new.value := 1;
FOR i IN 1..l_val LOOP
INSERT INTO {TABLE HERE}
VALUES (:new.name, 1);
END LOOP;
END IF;
END {TRIGGER NAME};
/
You need to use view and instead of trigger.
Creating table create table testing_trig (c char(1), i integer);
Creating view create or replace view testing_trig_view as select * from testing_trig;
Creating trigger
CREATE OR REPLACE TRIGGER testing_trg
INSTEAD OF INSERT
ON testing_trig_view
BEGIN
FOR i IN 1 .. :NEW.i
LOOP
INSERT INTO testing_trig VALUES (:NEW.c, 1);
END LOOP;
END;
/
Insert into view insert into testing_trig_view values ('A', 3);
Validate
SQL> select * from testing_trig;
C I
- ----------
A 1
A 1
A 1

Sync between two tables and show the result in an oracle function

I am making an oracle function that sync values between two tables and My intention is to show a string that show how many rows affected and displays it when user execute the function.
my function creation is like this
CREATE OR REPLACE FUNCTION WELTESADMIN.DUM_MST_SYNC(PROJNAME IN VARCHAR2)
RETURN NUMBER IS NUM_ROWS NUMBER;
BEGIN
MERGE INTO MASTER_DRAWING DST
USING (SELECT WEIGHT_DUM, HEAD_MARK_DUM FROM DUMMY_MASTER_DRAWING) SRC
ON (DST.HEAD_MARK = SRC.HEAD_MARK_DUM)
WHEN MATCHED THEN UPDATE SET DST.WEIGHT = SRC.WEIGHT_DUM
WHERE DST.PROJECT_NAME = SRC.PROJECT_NAME_DUM
AND DST.PROJECT_NAME = PROJNAME;
dbms_output.put_line( sql%rowcount || ' rows merged' );
END;
if i execute the begin part in the TOAD or SQL Developer i can see how many rows affected. My target is to collect this function into a procedure and when user wants to sync tables they just need to run the procedure with PROJNAME value supplied for specific project.
Please help me on how to improve this code,
Best regards
You can use SQL%ROWCOUNT to get the number of rows affected by the MERGE. Add the following statement in your code immediately after the MERGE :
dbms_output.put_line( sql%rowcount || ' rows merged' );
To return this value, declare a NUMBER variable and assign the sql%rowcount value to it. And then return that value. Something like :
Function
.......
Return NUMBER
.......
num_rows NUMBER;
......
Begin
Merge....
num_rows := SQL%ROWCOUNT;
RETURN num_rows;
END;
And, you don't need a procedure to execute the function. You can execute in SQL :
select function(project_name)
from dual
/
Update Since OP is trying to use DML inside a function, need to make it autonomous transaction to be able to perform DML without raising the ORA-14551.
You could use the directive pragma autonomous_transaction. This will run the function into an independent transaction that will be able to perform DML without raising the ORA-14551. However, remember, the results of the DML will be committed outside of the scope of the parent transaction. If you have only single transaction, you could use the workaround that I suggested. Add, PRAGMA AUTONOMOUS_TRANSACTION; immediately after the RETURN statement before BEGIN.
CREATE OR REPLACE
FUNCTION WELTESADMIN.DUM_MST_SYNC(
PROJNAME IN VARCHAR2)
RETURN NUMBER
IS
num_rows NUMBER;
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
MERGE INTO MASTER_DRAWING DST USING
(SELECT WEIGHT_DUM, HEAD_MARK_DUM FROM DUMMY_MASTER_DRAWING
) SRC ON (DST.HEAD_MARK = SRC.HEAD_MARK_DUM)
WHEN MATCHED THEN
UPDATE
SET DST.WEIGHT = SRC.WEIGHT_DUM
WHERE DST.PROJECT_NAME = SRC.PROJECT_NAME_DUM
AND DST.PROJECT_NAME = PROJNAME;
num_rows := SQL%ROWCOUNT;
COMMIT;
RETURN num_rows;
END;
/

Calling a function in a before delete trigger

id like to call this function:
CREATE OR REPLACE PACKAGE orders_salary_manage2 AS
FUNCTION total_calc(p_order in NUMBER)
RETURN NUMBER;
END;
CREATE OR REPLACE PACKAGE BODY orders_salary_manage2 AS
tot_orders NUMBER;
FUNCTION total_calc(p_order in NUMBER)
RETURN NUMBER
IS
c_price product.unit_price%type;
c_prod_desc product.product_desc%type;
v_total_cost NUMBER := 0;
CURSOR c1 IS
SELECT product_desc, unit_price
FROM product
WHERE product_id IN (SELECT fk2_product_id
FROM order_line
WHERE fk1_order_id = p_order);
BEGIN
OPEN c1;
LOOP
FETCH c1 into c_prod_desc, c_price;
v_total_cost := v_total_cost + c_price;
EXIT WHEN c1%notfound;
END LOOP;
CLOSE c1;
return v_total_cost;
END;
from this trigger:
CREATE OR REPLACE TRIGGER trg_order_total
BEFORE DELETE ON placed_order
FOR EACH ROW
DECLARE
v_old_order NUMBER := :old.order_id;
BEGIN
total_calc(v_old_order);
END;
but i keep getting this error, note there is no error number just this:
Error at line 4: PL/SQL: Statement ignored
BEFORE DELETE ON placed_order
FOR EACH ROW
DECLARE
v_old_order NUMBER := :old.order_id;
BEGIN
im new to pl/sql and just not sure what is causing the problem. When a user deletes an order from the orders table the trigger should call the function to add up all the products on the order.
Thank you
(Considering your Package compiled with no errors) Use-
ret_val:= orders_salary_manage2.total_calc(v_old_order);
The ret_val must be a NUMBER since the package function total_calc returns a NUMBER. A function MUST always return its outcoume to a variable (like ret_val) depending on the type of the return value the data type of the variable must be declared.
The syntax to call Pacakaged Procedures and functions is -
<RETURN_VARIABLE> := PACKAGE_NAME.<FUNCTION_NAME>();
PACKAGE_NAME.<PROCEDURE_NAME>(); --Since Procedure never returns
Also note that if your package is in a different SCHEMA and has no PUBLIC SYNONYM then you will have to prefix the schema name like <SCHEMA>.PACKAGE_NAME.<FUNCTION_NAME>() (considering the calling schema has execute permissions on the package).
So,
CREATE OR REPLACE TRIGGER trg_order_total
BEFORE DELETE ON placed_order
FOR EACH ROW
DECLARE
v_old_order NUMBER := :old.order_id;
v_ret_val NUMBER := 0;
BEGIN
v_ret_val := orders_salary_manage2.total_calc(v_old_order);
--...Do stuff with v_ret_val
END;

Resources