0
follows the statement:
If the employee department code is not Insert or if it does not exist in the table , assign to it the value standard 20;
And I made the following code:
create or replace trigger checar_cod_dept after insert or update of DPT_ID
on EMPREGADOS for each row when (DPT_ID not in (select ID from DEPARAMENTO))
begin
:new.id := 20;
end;
tables:
CREATE TABLE EMPREGADOS (
NOME VARCHAR2(50) PRIMARY KEY,
SALARIO number(2),
DPT_ID NUMBER,
CONSTRAINT DPT_ID_FK FOREIGN KEY (DPT_ID) REFERENCES DEPARTAMENTO(ID)
);
CREATE TABLE DEPARTAMENTO (
ID NUMBER PRIMARY KEY,
NOME VARCHAR2(50)
);
With the code I tried to use, the error because you can’t use Queries... I couldn’t think of another way.
Thank you
Hi hi hi, at first glance I would say that you do not need triggers the "default on null 20" in create table or alter table, would solve the problem, additionally it may be necessary to use "CONSTRAINT DPT_ID_FK FOREIGN KEY (DPT_ID) REFERENCES DEPARTMENT(ID) ENABLE NOVALIDATE;" not to validate constraints if data exists and you make an alter table.
– Ernesto Casanova
So I believe my teacher requested this exercise with Trigger for educational purposes only
– dani
Did he really ask with Rigger? In fact, the use of triggers in a database should be avoided (for example, by loss of performance), and as already noted there are other limitations. As for the exercise and what idea I think it would be to see the solution presented, what it seems to me is something as simple as a default, validates if it solves, however there is something you have to guarantee, the ID 20 will always have to exist in the DEPARTMENT table, this can be generated at the time of creating the database when running a default data SEED, then inject this value always.
– Ernesto Casanova
By securing the ID 20 in the DEPARTMENT table you are ensuring the integrity of the ER database. You have here more detail on this.
– Ernesto Casanova
create or replace Trigger checar_cod_dept after Insert or update of DPT_ID on EMPREGADOS for each Row Begin If :new.dpt_id is null then :new.dpt_id := 20; end if; end;
– Motta
It should not be BEFORE Insert or update?
– anonimo
Yes, before of course !
– Motta