Insert trigger if record exists - Oracle - 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

Related

Creating a trigger to insert and remove rows

I have been given an assignment to create a trigger that works when tables are inserted or updated or deleted in a table. If it is a delete or update then the table must store the older values before the action on another table. If it is insert then the new row should be added to the new table. Also it should include the number of rows that are affected by each action. So far this is what I have done:
CREATE OR REPLACE TRIGGER archive_update
BEFORE INSERT OR UPDATE ON EMPLOYEE
FOR EACH ROW
BEGIN
INSERT INTO archive_emp(EMP_ID, FIRST_NAME, LAST_NAME, BIRTH_DAY,
SEX, SALARY, SUPER_ID, BRANCH_ID)
VALUES(:new.EMP_ID, :new.FIRST_NAME, :new.LAST_NAME,
:new.BIRTH_DAY, :new.SEX, :new.SALARY, :new.SUPER_ID, :new.BRANCH_ID);
END;
To check the dml operation you may use an IF condition with appropriate dml predicate
CREATE OR REPLACE TRIGGER archive_update
BEFORE
INSERT OR UPDATE ON EMPLOYEE
FOR EACH ROW
BEGIN
IF UPDATING OR DELETING THEN --You may add this
INSERT INTO archive_emp( emp_id, first_name, last_name,
birth_day, sex,salary,super_id,branch_id
) VALUES (:old.emp_id, :old.first_name,:old.last_name,:old.birth_day,
:old.sex,:old.salary,:old.super_id,:old.branch_id
);
ELSIF INSERTING THEN --and this
INSERT INTO archive_emp( emp_id, first_name, last_name,
birth_day, sex,salary,super_id,branch_id
) VALUES (:new.emp_id, :new.first_name,:new.last_name,:new.birth_day,
:new.sex,:new.salary,:new.super_id,:new.branch_id
);
END IF;
END;
/

What is the proper way to create an update trigger with a variable getting value from the same table?

I'm creating a update trigger where an employee can never have a salary that is greater than the president's. However I need to subquery the president's salary for comparison and the "new" updated employee's salary.
I originally had the the subquery using from the from employees table but had to make a new table because of the mutating table problem. I don't think creating a new table is plausible solution for a real implementation.
Is there a way I can save the president's salary without creating a new table?
CREATE OR REPLACE TRIGGER prevent_salary
BEFORE UPDATE ON employees
FOR EACH ROW
declare pres_sal number(8,2);
BEGIN
select salary into pres_sal from employees_salary where job_id='AD_PRES';--employees_salary was employees but that gives mutating error
IF (:new.salary > pres_sal)
THEN UPDATE employees
SET salary = :old.salary
WHERE employee_id = :old.employee_id;
END IF;
END;
One way to do it is to save off the president's salary in a BEFORE STATEMENT trigger and then use that in the FOR EACH ROW trigger.
"Compound Triggers", which have been around at least since version 11.1, offer a nice way to do that all in one place.
Here is an example:
CREATE OR REPLACE TRIGGER prevent_salary
FOR UPDATE OF salary ON employees
COMPOUND TRIGGER
pres_sal NUMBER;
BEFORE STATEMENT IS
BEGIN
select salary
into pres_sal
from employees
where job_id='AD_PRES';
END BEFORE STATEMENT;
BEFORE EACH ROW IS
BEGIN
:new.salary := least(:new.salary, pres_sal);
END BEFORE EACH ROW;
END prevent_salary;
You may try this :
CREATE OR REPLACE TRIGGER prevent_salary
BEFORE UPDATE ON employees
FOR EACH ROW
declare pres_sal number(8,2);
BEGIN
select salary into pres_sal from employees_salary where job_id='AD_PRES';--employees_salary was employees but that gives mutating error
IF (:new.salary > pres_sal)
Raise_Application_Error (-20101, 'An employee''s salary couldn''t exceed president''s !');
END IF;
END;

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;

ORACLE Trigger INSERT On UPDATE

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.

Resources