ORACLE Trigger INSERT On UPDATE - oracle

All,
I am just trying to create a trigger that will pick a whole record from TABLE EMP and insert it in TABLE EMP_ARCHIVE on an UPDATE attempt (As the name suggests, EMP_ARCHIVE Table is just a history table to store the changes made on the mail EMP Table). Both table has the same fields/columns. Following is the trigger i am trying to create. I know there is something wrong but couldn't figure out. It throws error at the '(' following the INSERT command. Any help would be appreciated.
Forgive me if there's some fundamental error as i am a newbie to these.
CREATE OR REPLACE TRIGGER Save_EMP_Changes
BEFORE UPDATE ON EMP
FOR EACH ROW
BEGIN
INSERT INTO EMP_ARCHIVE
(
emp_id, emp_name,
emp_age, emp_sex,
emp_active
)
SELECT
:old.emp_id, :old.emp_name,
:old.emp_age, :old.emp_sex,
:old.emp_active
FROM EMP
WHERE emp_id = :old.emp_id
END;

No need to select from the table:
CREATE OR REPLACE TRIGGER Save_EMP_Changes
BEFORE UPDATE ON EMP
FOR EACH ROW
BEGIN
INSERT INTO EMP_ARCHIVE
(
emp_id, emp_name,
emp_age, emp_sex,
emp_active
)
VALUES
( :old.emp_id, :old.emp_name,
:old.emp_age, :old.emp_sex,
:old.emp_active
);
END;
Btw: in Oracle 11 you can completely automate this by create an FLASHBACK ARCHIVE for those tables. No trigger or any other hassle.

I know this is a bit old question. But figured i put another idea down for anybody else that comes across this question like i just did. In the past i've done the following when doing the same archiving process.
CREATE OR REPLACE TRIGGER Save_EMP_Changes
BEFORE UPDATE ON EMP
FOR EACH ROW
BEGIN
INSERT INTO EMP_ARCHIVE
(
emp_id, emp_name,
emp_age, emp_sex,
emp_active, revision_cnt
)
SELECT
:old.emp_id, :old.emp_name,
:old.emp_age, :old.emp_sex,
:old.emp_active, nvl(max(revision_cnt)+1, 1)
FROM EMP
WHERE emp_id = :old.emp_id
END;
HTH others.

Related

Insert trigger if record exists - Oracle

I have tables:
DEPARTMETS with dep_id(number), dep_name(varchar), manager_id(number) fields.
EMPLOYEES with employee_id(number), name(varchar), salary(number), manager_id(number)
I want to create a trigger which it is responsible for check if exists manager_id into table DEPARTMENTS when data is inserted or updated to table EMPLOYEES
Trigger could be something like:
create or update trigger manager_exists
before insert or update on employees
for each row
begin
if exists **new id** into Departments then
INSERT DATA IN EMPLOYEES
else
"Error: MANAGER_ID doesnt exists in Departments"
end if;
end manager_exists;
But I can't figure out how to create this trigger.
Note:I need it to be a trigger please. HELP!
This is how I understood the question:
create or replace trigger manager_exists
before insert or update on employees
for each row
declare
l_mgr number;
begin
select 1
into l_mgr
from dual
where exists (select null
from departments d
where d.manager_id = :new.manager_id
);
exception
when no_data_found then
raise_application_error(-20000, 'That manager does not exist in DEPARTMENTS');
end manager_exists;
In other words:
check whether MANAGER_ID you're trying to insert into EMPLOYEES table exists in DEPARTMENTS table
though, that doesn't make much sense to me; I'd say that you should check it vice versa - check whether MANAGER_ID you're trying to insert into DEPARTMENTS exists in EMPLOYEES table ... but that's not what you wrote (or I misunderstood what you said)
if so, fine, don't do anything (in a trigger); insert or update statement which caused the trigger to fire will do the job
if not, raise an error

Using INSERT INTO... SELECT in TRIGGER

The question I am going to ask is already there. But I don't have answer for this.
Please refer the below link.
ORACLE TRIGGER INSERT INTO ... (SELECT * ...)
I have around 600 columns in a table. After each insert in this table I need to insert the new row in another backup table.
Please tell how to use "INSERT INTO TABLE_NAME2 SELECT * FROM TABLE_NAME1" query in trigger.
Note: Without specifying columns in insert or select clause
Structure of both table is same. Specifying all the column name in trigger is difficult and also if new columns added, we need to add in trigger as well.
SQL> CREATE or REPLACE TRIGGER emp_after_insert AFTER INSERT ON emp
FOR EACH ROW
DECLARE
BEGIN
insert into emp_backup values (:new.empid, :new.fname, :new.lname);
DBMS_OUTPUT.PUT_LINE('Record successfully inserted into emp_backup table');
END;
reference:
http://www.tech-recipes.com/rx/19839/oracle-using-the-after-insert-and-after-update-triggers/
You should use COMPOUND TRIGGER. This trigger should look like this:
CREATE OR REPLACE TRIGGER t_copy_table1
FOR INSERT ON table1
COMPOUND TRIGGER
v_id number;
BEFORE EACH ROW IS
BEGIN
v_id := :new.id;
END BEFORE EACH ROW;
AFTER STATEMENT IS
BEGIN
insert into table2 select * from table1 where id=v_id;
END AFTER STATEMENT;
END t_copy_table1;

use the same auto increment trigger in oracle for many tables

I created a database in MySQL with ~10 tables, each starting with the column
SN INT NOT NULL AUTO_INCREMENT
SN doesn't mean anything, just the primary to differentiate between possibly repeating/similar names/titles, etc
I'm moving it to Oracle now, and found this post here on stackoverflow to make the trigger to auto increment the SN field. Basically,
CREATE SEQUENCE user_seq;
CREATE OR REPLACE TRIGGER user_inc
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
SELECT user_seq.NEXTVAL
INTO :new.SN
FROM dual;
END;
/
Now, how can I rewrite that trigger once to apply to all the other tables? Because otherwise I have to rewrite it for many tables, just changing the trigger name and sequence name... I was picturing something like:
BEFORE INSERT ON users OR other_table OR another_one
I also found this post here, but the one answer there isn't helpful because I think it's reasonable for many tables to have the same SN field, or I'm misunderstanding the point.
Also, not Oracle 12c so no identity columns
Thanks in advance
I was going to just comment on the first post I mentioned but I can't comment without more reputation points :/
Creating a trigger referencing many tables in Oracle is not possible,
What you can do is to generate the triggers with a PL/SQL statement.
Below is an example on how could you achieve this
drop table tab_a;
drop table tab_b;
drop table tab_c;
drop sequence seq_tab_a_id;
drop sequence seq_tab_b_id;
drop sequence seq_tab_c_id;
--create test tables
create table tab_a (SN number, otherfield varchar2(30), date_field date);
create table tab_b (SN number, otherfield varchar2(30), date_field date);
create table tab_c (SN number, otherfield varchar2(30), date_field date);
-- this pl/sql block creates the sequences and the triggers
declare
my_seq_create_stmt varchar2(2000);
my_trigger_create_stmt varchar2(2000);
begin
for i in (select table_name
from user_tables
-- remember to change this where condition to filter
-- the tables that are relevant for you
where table_name in ('TAB_A', 'TAB_B', 'TAB_C') )loop <<TableLoop>>
my_seq_create_stmt := 'CREATE SEQUENCE '||'SEQ_'||i.table_name||'_ID '
||CHR(13)||' START WITH 1 INCREMENT BY 1 NOCYCLE ';
execute immediate my_seq_create_stmt;
my_trigger_create_stmt := 'CREATE OR REPLACE TRIGGER '||'TRG_'||i.Table_name||'_ID_BI '||' BEFORE INSERT ON '||i.table_name||' FOR EACH ROW '
||CHR(13)||'BEGIN '
||CHR(13)||' SELECT '||'SEQ_'||i.table_name||'_ID'||'.NEXTVAL '
||CHR(13)||' INTO :new.SN '
||CHR(13)||' FROM dual; '
||CHR(13)||'END; ';
execute immediate my_trigger_create_stmt;
end loop TableLoop;
end;
/
-- test the triggers and the sequences
insert into tab_a (otherfield, date_field) values ('test 1',sysdate);
insert into tab_a (otherfield, date_field) values ('test 2',sysdate);
commit;
Select * from tab_a;

Can I directly define a trigger in all_triggers table on a table?

I am performing an archival process on a huge database and it involves deleting the production active table and renaming another table to be the new production table. When dropping the production active table, the triggers also get deleted. So I am just taking a backup of the triggers defined on my table using
select * from all_triggers where table_name=mytablename;
My question is, can I directly copy these triggers in to the all_triggers table after I rename my other table to be the new production active table? Will the triggers still work?
Same question for defining indexes and constraints too.
Copying the triggers from one table to another can be done by copying DDL, and not updating all_triggers table. This can be done by using DBMS_METADATA.
The closest practical example I found here: Copy Triggers when you Copy a Table
The following script can be amended as per your need:
declare
p_src_tbl varchar2(30):= 'PERSONS'; --your table name
p_trg_tbl varchar2(30):= 'PSN2'; --your trigger name
l_ddl varchar2(32000);
begin
execute immediate 'create table '||p_trg_tbl||' as select * from '||p_src_tbl||' where 1=2';
for trg in (select trigger_name from user_triggers where table_name = p_src_tbl) loop
l_ddl:= cast(replace(replace(dbms_metadata.get_ddl( 'TRIGGER', trg.trigger_name),p_src_tbl,p_trg_tbl),trg.trigger_name,substr(p_trg_tbl||trg.trigger_name, 1, 30)) as varchar2);
execute immediate substr(l_ddl, 1, instr(l_ddl,'ALTER TRIGGER')-1);
end loop;
end;
/
No, you cannot directly manipulate data dictionary tables. You can't insert data directly into all_triggers (the same goes for any data dictionary table). I guess you probably could given enough hacking. It just wouldn't work and would render your database unsupported.
The correct way to go is to script out your triggers and reapply them later. If you want to do this programmatically, you can use the dbms_metadata package. If you want to get the DDL for each of the triggers on a table, you can do something like
select dbms_metadata.get_ddl( 'TRIGGER', t.trigger_name, t.owner )
from all_triggers t
where table_owner = <<owner of table>>
and table_name = <<name of table>>
To replicate your scenario i have prepared below snippet. Let me know if this helps.
--Simple example to copy Trigger from one table to another
CREATE TABLE EMP_V1 AS
SELECT * FROM EMP;
--Creating Trigger on Old Table for Example purpose
CREATE OR REPLACE TRIGGER EMP_OLD_TRIGGER
AFTER INSERT OR UPDATE ON EMP FOR EACH ROW
DECLARE
LV_ERR_CODE_OUT NUMBER;
LV_ERR_MSG_OUT VARCHAR2(2000);
BEGIN
dbms_output.put_line('Your code for data Manipulations');
--Like Insert update or DELETE activities
END;
-- To replace this trigger for emp_v2 table
set serveroutput on;
DECLARE
lv_var LONG;
BEGIN
FOR i IN (
SELECT OWNER,TRIGGER_NAME,DBMS_METADATA.GET_DDL('TRIGGER','EMP_OLD_TRIGGER') ddl_script FROM all_triggers
WHERE OWNER = 'AVROY') LOOP
NULL;
lv_var:=REPLACE(i.ddl_script,'ON EMP FOR EACH ROW','ON EMP_V1 FOR EACH ROW');
dbms_output.put_line(substr(lv_var,1,INSTR(lv_var,'ALTER TRIGGER',1)-1));
EXECUTE IMMEDIATE 'DROP TRIGGER '||I.TRIGGER_NAME;
EXECUTE IMMEDIATE lv_var;
END LOOP;
END;
--Check if DDL manipulation has been done for not
SELECT OWNER,TRIGGER_NAME,DBMS_METADATA.GET_DDL('TRIGGER','EMP_OLD_TRIGGER') ddl_script FROM all_triggers
WHERE OWNER = 'AVROY';
---------------------------------OUTPUT----------------------------------------
"
CREATE OR REPLACE TRIGGER "AVROY"."EMP_OLD_TRIGGER"
AFTER INSERT OR UPDATE ON EMP_V1 FOR EACH ROW
DECLARE
LV_ERR_CODE_OUT NUMBER;
LV_ERR_MSG_OUT VARCHAR2(2000);
BEGIN
dbms_output.put_line('Your code for data Manipulations');
--Like Insert update or DELETE activities
END;
"
-----------------------------OUTPUT----------------------------------------------

Create trigger to insert into another table

I have some problem executing the trigger below:
CREATE OR REPLACE TRIGGER AFTERINSERTCREATEBILL
AFTER INSERT
ON READING
FOR EACH ROW
DECLARE
varReadNo Int;
varMeterID Int;
varCustID Varchar(10);
BEGIN
SELECT SeqReadNo.CurrVal INTO varReadNo FROM DUAL;
Select MeterID INTO varMeterID
From Reading
Where ReadNo = varReadNo;
Select CustID INTO varCustID
From Address A
Join Meter M
on A.postCode = M.postCode
Where M.MeterID = varMeterID;
INSERT INTO BILL VALUES
(SEQBILLNO.NEXTVAL, SYSDATE, 'UNPAID' , 100 , varCustID , SEQREADNO.CURRVAL);
END;
Error Message:
*Cause: A trigger (or a user defined plsql function that is referenced in
this statement) attempted to look at (or modify) a table that was
in the middle of being modified by the statement which fired it.
*Action: Rewrite the trigger (or function) so it does not read that table.
Does it mean that I am not suppose to retrieve any details from table Reading?
I believe that the issue occur as I retrieving data from Table Reading while it is inserting the value:
SELECT SeqReadNo.CurrVal INTO varReadNo FROM DUAL;
Select MeterID INTO varMeterID
From Reading
Where ReadNo = varReadNo;
It's there anyway to resolve this? Or is there a better method to do this? I need to insert a new row into table BILL after entering the table Reading where the ReadNo need to reference to the ReadNo I just insert.
You cannot retrieve records from the same table in a row trigger. You can access values from actual record using :new and :old (is this your case?). The trigger could then be rewritten to
CREATE OR REPLACE TRIGGER AFTERINSERTCREATEBILL
AFTER INSERT
ON READING
FOR EACH ROW
DECLARE
varCustID Varchar(10);
BEGIN
Select CustID INTO varCustID
From Address A
Join Meter M
on A.postCode = M.postCode
Where M.MeterID = :new.MeterID;
INSERT INTO BILL VALUES
(SEQBILLNO.NEXTVAL, SYSDATE, 'UNPAID' , 100 , varCustID , SEQREADNO.CURRVAL);
END;
If you need to query other record from READING table you have to use a combination of statement triggers, row trigger and a PLSQL collection. Good example of this is on AskTom.oracle.com
Make sure that you have the necessary permissions on all the tables and access to the sequences you're using in the insert.
I haven't done Oracle in awhile, but you can also try querying dba_errors (or all_errors) in order to try and get more information on why your SP isn't compiling.
Something to the tune of:
SELECT * FROM dba_errors WHERE owner = 'THEOWNER_OF_YOUR_SP';
Add exception handling in your trigger and see what is happening, by doing it would be easy for you to track the exceptions.
CREATE OR REPLACE TRIGGER AFTERINSERTCREATEBILL
AFTER INSERT
ON READING
FOR EACH ROW
DECLARE
varCustID Varchar(10);
BEGIN
-- your code
EXCEPTION
WHEN NO_DATA_FOUND
THEN
DBMS_OUTPUT.PUT_LINE(TO_CHAR(SQLERRM(-20299)));
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(TO_CHAR(SQLERRM(-20298)));
END;
we can combined insert and select statement
CREATE OR REPLACE TRIGGER AFTERINSERTCREATEBILL
AFTER INSERT
ON READING
FOR EACH ROW
DECLARE
varCustID Varchar(10);
BEGIN
insert into bill
values
select SEQBILLNO.NEXTVAL,
SYSDATE,
'UNPAID' ,
100 ,
CustID,SEQREADNO.CURRVAL
From Address A
Join Meter M
on A.postCode = M.postCode
Where M.MeterID = :new.MeterID;
END;
try the above code.

Resources