Trigger of two tables in an audit - oracle

Good morning, I am trying to audit two tables, and I have investigated that it cannot be done, therefore I explain what I wanted to do:
I have two tables (Participante, Actividad) which are joined by a third table (Part_Actividad)
I want to audit the Participants table, but in the same way I need the Id of the activity to know in which activity the data of a participant is changed.
Ideas I had
Create a trigger like the following
CREATE OR REPLACE TRIGGER Tri_Auditoria
AFTER INSERT ON Participante
FOR EACH ROW
DECLARE
v_Participante_ID Participante.Participante_ID%TYPE;
v_Actividad_ID Part_Actividad.Actividad_ID%TYPE;
BEGIN
SELECT participante_ID INTO v_Participante_ID
FROM Participante;
SELECT Actividad_ID INTO v_Actividad_ID
FROM Part_Actividad
WHERE PartAct_ID = v_Participante_ID;
INSERT INTO Auditoria(Auditoria_ID, Actividad_ID, Participante_ID, TipPart_ID_Ant, Part_P_Nombre_Ant, Part_P_Apell_Ant, Part_Cedula_Ant, Part_Genero_ant, Part_FNaci_Ant, Aud_Operacion, Usuario_Modificador, Fecha_Modificacion)
VALUES (sec_Auditoria.nextval, v_Actividad_ID, :new.Participante_ID,:new.TipPart_ID,:new.Part_P_Nom,:new.Part_P_Apell,:new.Part_Cedula,:new.Part_Genero,:new.Part_FNaci,'I',USER,sysdate);
END Tri_Auditoria;
/
Result:
When I insert data into the participante table, it is not inserted and it sends a trigger error.

Mutating table error, isn't it? That's because you're selecting from the same table which caused trigger to fire, and that's not allowed.
Anyway, you shouldn't do that because you have that value in disposal - just reference it using the :new pseudorecord, such as
CREATE OR REPLACE TRIGGER Tri_Auditoria
AFTER INSERT ON Participante
FOR EACH ROW
DECLARE
v_Actividad_ID Part_Actividad.Actividad_ID%TYPE;
BEGIN
SELECT Actividad_ID
INTO v_Actividad_ID
FROM Part_Actividad
WHERE PartAct_ID = :new.participante_ID; --> this
INSERT INTO Auditoria
(Auditoria_ID, Actividad_ID, Participante_ID,
TipPart_ID_Ant, Part_P_Nombre_Ant, Part_P_Apell_Ant,
Part_Cedula_Ant, Part_Genero_ant, Part_FNaci_Ant,
Aud_Operacion, Usuario_Modificador, Fecha_Modificacion)
VALUES (sec_Auditoria.nextval, v_Actividad_ID, :new.Participante_ID,
:new.TipPart_ID,:new.Part_P_Nom,:new.Part_P_Apell,
:new.Part_Cedula,:new.Part_Genero,:new.Part_FNaci,
'I',USER,sysdate);
END Tri_Auditoria;
/

Related

Triggers involving two tables

I have two relations(tables) namely and 'department' and 'employee'
create table department(depno numeric(5),depname varchar2(10),deplocation varchar2(7));
create table employee(empno numeric(5),empname varchar2(20),designation varchar2(20),depno numeric(5));
I'm trying to write a database trigger before deleting each row on table department deletes
corresponding department employees from employee table..
My code looks like
create or replace trigger tri before delete on department for each row
begin
delete from employee where depno=:old.depno;
end;
I inserted few data into my relation and tried to delete one of them having the depno as 2
'''delete from department where depno=2;'''
But it shows an error like this
ORA-04098: trigger 'SYSTEM.T1' is invalid and failed re-validation
Can you please help me with this or provide me an alternative solution to this problem?

PL/SQL: Decide if insert or update a row in a trigger, which is the best way?

I need to write a trigger in Oracle PL/SQL (11g) before inserting each row that checks if a row exists: if it doesn't exists creates a new row, if it does exists updates the existing record.
Which is the best way to do that?
Thanks, Gianluca
What you want to do is a MERGE INTO:
MERGE INTO myTable t
USING (SELECT 'Smith' AS Name, 1 AS Id FROM DUAL) data -- put your data in here
ON (t.Id = data.Id) -- pk or other matching criteria
WHEN MATCHED
THEN
UPDATE SET t.name = data.name
WHEN NOT MATCHED
THEN
INSERT (Id, Name)
VALUES (data.Id, data.Name);
Buildiing a trigger is possible but no allowed/intended. You should't do this.
You'd try to abbort the insert and do something else. This is not a good idea, because of many thing: hidden logic in db, stupid-clients which are doing wrong things..
You can abort with an error, but it doesn't sound like you idea this way.
If you want to do it you could change to update. Never insert anything and implement a trigger before update, which checks if the row exists:
CREATE OR REPLACE TRIGGER myTableTrigger
BEFORE UPDATE
ON myTable
FOR EACH ROW
BEGIN
-- If row doesn't exist. Insert one before the update..
END;
Alternatively you could go the long way and build some views:
https://dba.stackexchange.com/questions/24047/oracle-abort-within-a-before-insert-trigger-without-throwing-an-exception

How to create TRIGGER with a reference to the triggered table?

Can I create an AFTER TRIGGER on a table and using that table in my SELECT query without getting mutating table error?
Example to a query I want to use.
This query will update number of times a certain status name is showing up in alert life cycle:
CREATE OR REPLACE TRIGGER COUNT_STEP
AFTER INSERT
ON STEPS
FOR EACH ROW
DECLARE
V_COUNT_SETP VARCHAR (10000);
BEGIN
SELECT COUNT (STATUS_NAME)
INTO V_COUNT_SETP
FROM (SELECT A.ALERT_ID, S.STATUS_NAME
FROM ALERTS A, ALERT_STATUSES S, STEPS ST
WHERE :NEW.ALERT_INTERNAL_ID = A.ALERT_INTERNAL_ID
AND ST.ALERT_STATUS_INTERNAL_ID = S.STATUS_INTERNAL_ID
AND S.STATUS_NAME IN ('Auto Escalate'))
GROUP BY ALERT_ID;
UPDATE ALERTS A
SET A.COUNT = V_COUNT_ESC
WHERE A.ALERT_INTERNAL_ID = :NEW.ALERT_INTERNAL_ID;
END;
/
The table I'm inserting a record to is also needed for counting the number of step occurrences since it's stores the alert id and all the steps id it had.
You need to be a bit more clearer in your questions. But, from what i understood, you need to create a trigger on a table, and perform a select for that same table. That gives you a mutanting table error. To bypass that, you need to perform a compound trigger on that table. Something like this:
create or replace trigger emp_ct
for insert on employees compound trigger
v_count number; -- Add variable here
before statement is
begin
-- PERFORM YOUR SELECT AND SEND TO A VARIABLE
end before statement;
after each row is
begin
-- DO WANT YOU WANTED TO DO. USE THE VARIABLE
end after each row;
end;
basically, with a compound trigger, you can capture every trigger event. By doing that, allows to query the table you're capturing.

After insert in one table, insert into another table in Oracle APEX

What I would like to do is;
after I insert some data into table1, I would like some of that data automatically inserted into table2, such as the primary key from table1 inserted into table2 as a foreign key.
Is this done using a trigger.
Not sure where to start looking first.
Cheers
Brian
Yes you can do that through trigger. You can do it like this:
CREATE OR REPLACE TRIGGER my_trigger
before INSERT ON table1
REFERENCING NEW AS NEW
for each row
BEGIN
insert into table2(fk_column,column1) values(:new.pk_column_of_table1,'value1');
END;
you can create a trigger as #vance said and you can use returning into clause if you are populating some of the columns dynamically
INSERT INTO t1 VALUES (t1_seq.nextval, 'FOUR')
RETURNING id INTO l_id;
have a look here

TRIGGER Oracle to prevent updating or inserting

I am having problems with this code below, which is a trigger used in Oracle SQL:
CREATE OR REPLACE TRIGGER TRG_TUTOR_BLOCK
BEFORE INSERT OR UPDATE ON tutors
FOR EACH ROW
DECLARE
BEGIN
IF :new.tutorName = :old.tutorName
THEN
RAISE_APPLICATION_ERROR(-20101, 'A tutor with the same name currently exists.');
ROLLBACK;
END IF;
END;
/
This trigger is used to prevent users from entering the same tutor name at different records.
After I insert two records with the same tutorname, the trigger does not block me from inserting it. Is there anyone can tell me what are the problems with this coding? Here are the sample format and insert values:
INSERT INTO tutors VALUES (tutorID, tutorName tutorPhone, tutorAddress, tutorRoom, loginID);
INSERT INTO tutors VALUES ('13SAS01273', 'Tian Wei Hao', '019-8611123','No91, Jalan Wangsa Mega 2, 53100 KL', 'A302', 'TianWH');
Trigger in Kamil's example will throw ORA-04091, you can see this with your own eyes here. ROLLBACK in a trigger is unnecessary, it runs implicitly when a trigger makes a statement to fail.
You can prohibit any DML on table by altering it with read only clause:
alter table tutors read only;
At last, integrity should be declarated with integrity constraints and not with triggers.
Good luck!
You don't need a trigger for this in Oracle.
You can do it with an "unique index" on the tutorName column (see http://docs.oracle.com/cd/B28359_01/server.111/b28310/indexes003.htm#i1106547).
Note: about your trigger, it fails on checking for another record with the same tutorName because it's not scanning the tutors table for another record with the same tutorName, it's just comparing the tutorName values of the row you are creating (in this case, old.tutorName is just NULL, because the row doesn't exist yet).
Check the case in yours trigger body
IF :new.tutorName = :old.tutorName
It returns true only if 'tutorName' value is the same in new and old record. When you'll trying to updat some value you'll get
IF 'someTutorName' = 'someTutorName'
which will return TRUE.
Inserting row cannot fire this rule because you're trying to compare something like that:
'someTutorName' = NULL
This case always returns FALSE.
Try to use something like that
CREATE OR REPLACE TRIGGER TRG_TUTOR_BLOCK
BEFORE INSERT OR UPDATE ON tutors
FOR EACH ROW
DECLARE
rowsCount INTEGER;
BEGIN
SELECT COUNT(*) FROM tutors WHERE tutorName is :new.tutorName INTO rowsCount;
IF rowsCount > 0
THEN
RAISE_APPLICATION_ERROR(-20101, 'A tutor with the same name currently exists.');
ROLLBACK;
END IF;
END;
/
But the best solution is the one mentioned by friol - use unique index by executing SQL like this
ALTER TABLE tutors
ADD CONSTRAINT UNIQUE_TUTOR_NAME UNIQUE (tutorName);
If you wanna completely ignore recording a row to a table you can follow these steps
rename table to something else and create a view with the same name and create an instead of trigger.
create table usermessages (id number(10) not null)
GO
alter table usermessages rename to xusermessages
GO
create or replace view usermessages as (select * from xusermessages)
GO
create or replace trigger usermessages_instead_of_trg
instead of insert or update on usermessages
for each row
begin
Null ;
end ;
GO
insert into usermessages(123)
Live test available here below
http://sqlfiddle.com/#!4/ad6bc/2

Resources