I'm trying to create a trigger that controls cycles in a self-referencing table.
Unfortunately I've got an error. Could anyone tell me what I'm doing wrong?
CREATE OR REPLACE TRIGGER CHECK_CYCLE
BEFORE INSERT OR UPDATE ON DEPARTMENTS
FOR EACH ROW
BEGIN
IF :NEW.PARENT_ID =
(SELECT ID, PARENT_ID, NAME, LEVEL,
CONNECT_BY_ISLEAF AS ISLEAF,
PRIOR NAME AS PARENT_NAME,
CONNECT_BY_ROOT NAME AS ROOT
FROM DEPARTMENTS
START WITH PARENT_ID IS NULL
CONNECT BY PRIOR ID = PARENT_ID)
THEN
RAISE_APPLICATION_ERROR(20000, 'Sorry.');
END IF;
END;
Error(9,25): PLS-00103: Encountered the symbol "AS" when expecting one of the following:
, from
This seems to be the parser getting confused. If you remove the AS ROOT completely then it reverts to the expected PLS-00405: subquery not allowed in this context error. No idea why it is confused - you can run that query standalone - but since you can't do what you're attempting it's probably not worth worrying about too much.
Your subquery also has three columns and will return multiple rows, so comparing with the current row's scalar PARENT_ID isn't going to work. You could run your subquery separately and select the value you're actually interested in into a local variable, and check against that.
But you have a before-insert trigger and you're querying the table the trigger is against, so you'll get a mutating table exception anyway when you try to insert (or at least, if you try to insert multiple rows at once).
If I understand what you're trying to achieve, you can use an after-insert trigger instead:
create or replace trigger check_cycle
after insert or update on departments
declare
l_hascycle pls_integer;
begin
select max(connect_by_iscycle)
into l_hascycle
from departments
start with parent_id is null
connect by nocycle prior id = parent_id;
if l_hascycle = 1 then
raise_application_error(-20000, 'Sorry.');
end if;
end;
/
This uses the CONNECT_BY_ISCYCLE pseudocolumn, which will be zero for all rows if there is no cycling, and one for any column that cycles. Selecting and checking the max() of that means you'll have a single value of 0 or 1 in the local l_hascycle variable, and you can use that to decide whether to throw an exception.
Inserting a couple of test rows on top of existing non-cycling data such as:
ID PARENT_ID NAME
---------- ---------- ------------
1 Test
2 1 Test
... where the first new row is OK and the second would cause a cycle:
insert into departments (id, parent_id, name) values (3, 2, 'OK');
1 row inserted.
insert into departments (id, parent_id, name) values (2, 3, 'Cycles');
ORA-20000: Sorry.
ORA-06512: at "SCHEMA.CHECK_CYCLE", line 11
ORA-04088: error during execution of trigger 'SCHEMA.CHECK_CYCLE'
The first insert is still in effect (but not yet committed), the second was implicitly rolled back:
select * from departments:
ID PARENT_ID NAME
---------- ---------- ------------
1 Test
2 1 Test
3 2 OK
This won't catch cycles in data that is not connected to an existing tree culminating in a null parent, because of the start with clause; so for exampel with data you could insert 4,5 and 5,4 without raising an exception, as there is no route from either 4 or 5 to a row with a null parent. But that's a different issue and something you might want to test for separately.
It also can't see data from uncommitted changes in other sessions, so it's possible for two sessions to simultaneously insert rows that are valid independently but which still would form a cycle once both are committed.
I think I found the error in your query, it's in this line -
CONNECT_BY_ROOT NAME AS ROOT
which is not built correctly.
Try changing it to something like
CONNECT_BY_ROOT AS ROOT
Related
I have two back-end systems (the old one and the new one) that shares an Oracle DB.
In the older system, to save customers data, there are two tables
customers_A
ID NAME ETC
1 PETE ....
customers_B
ID NAME ETC
1 JOSH ...
2 ROSS ...
In the new system I've created a new table called All_Costumer, to join those tables.
This new table contains customer ID's of type A and B respectively.
All_Customers
ID ID_CUSTOMER_A ID_CUSTOMER_B
A19E----D2B0 1 null
A19E----D2B1 null 1
A19E----D2B2 null 2
So, when the new system creates a new customer of type A, data are inserted on customer_A and All_Customers tables, with customer of type B as well.
Currently, the old system is working too, and when a new customer of type A is created, data is inserted only on customer_A table, but I need that data in All_Customers too.
To solve this, I've created a TRIGGER with a MERGE INTO statement inside, to insert a row in All_Customers if doesn't exist on this table (when a new customer of type A are created by the older system)
CREATE OR REPLACE TRIGGER customers_trg
AFTER INSERT
ON customer_A
FOR EACH ROW
DECLARE
variables that doesn't matters
BEGIN
MERGE INTO all_customers
USING (SELECT :new.id id FROM customer_A where id = :new.id) customer
ON (all_customers.id_customer_a = customer.id)
WHEN NOT MATCHED THEN
INSERT (id, id_customer_a)
VALUES (SYS_GUID(), :new.id, null);
COMMIT;
END;
But when I try to create a new customer from the older system, I get this error:
ORA-04091: table **customer_A** is mutating, trigger/function may not see it
Any idea to solve this?
I've tried adding PRAGMA AUTONOMOUS_TRANSACTION; on DECLARE section, but didn't work.
Note: I can't modify the old system
The immediate issue is that you're querying table_a in a trigger against that table; but you don't need to. Your merge query
SELECT :new.id id FROM customer_A where id = :new.id
can simply do
SELECT :new.id id FROM dual
i.e. the clause becomes:
...
USING (SELECT :new.id id FROM dual) customer
ON (all_customers.id_customer_a = customer.id)
...
You also can't commit in a trigger - unless it's autonomous, which this shouldn't be. You said you'd tried that, but it breaks if the insert is rolled back, since the merged row will still exist. So hopefully that commit is just a hang-over from trying and rejecting that approach.
But it works in this db<>fiddle, anyway.
If you weren't adding the GUID you could get the same effect with a view:
create or replace view all_customers (id_customer_a, id_customer_b) as
select id, null from customers_a
union all
select null, id from customers_b;
db<>fiddle
I have form in which user add information of new born baby with his/her head family name. When add information into table then getting following errors
ORA-00001: unique constraint (PK) violated
ORA-06512: at trigger_name, line 21
ORA-04088: error during execution of trigger
Trigger:
CREATE OR REPLACE TRIGGER "DB_NAME"."TRG_NBB"
AFTER INSERT ON baby
FOR EACH ROW
WHEN (new.status = 'A') DECLARE
v_1 tab_1.col_1%type;
v_2 tab_2.col_2%type;
v_3 tab_2.col_3%type;
v_4 tab_2.col_4%type;
v_5 tab_2.col_5%type;
v_6 date;
newmofid number;
BEGIN
select max(nvl(col_2,0))+1 into newmofid from tab_2;
SELECT distinct col_1,col_2,to_char(col,'DD-MM-YYYY') INTO v_1,v_2,v_6
from table
where tcid = :new.tcid;
SELECT col_4,col_5,col_3 into v_4,v_5,v_3
from tab_2
where col_1 = v_1
and col_2 = v_2;
INSERT INTO tab_2 (all_columns)
VALUES(variable_names);
DBMS_OUTPUT.PUT_LINE('New Born Baby successfully added to member table');
END trg_nbb;
/
ALTER TRIGGER "DB_NAME"."TRG_NBB" ENABLE;
When I execute this sql query It's take 4 to 5 seconds and increment in values very quickly
select max(nvl(col_2,0))+1 into newmofid from tab_2;
Result:
6030819791
Again execute takes 3 to 4 seconds
Result:
6030819798
How to solve this problem?
Thanks
I suspect it is MAX + 1 that causes problems:
select max(nvl(col_2,0))+1 into newmofid from tab_2;
Such a principle is in most cases wrong and will fails, especially in a multi-user environment where two (or more) users at the same time fetch the same MAX + 1 value, do some processing, and - at the time of insert - one of them succeeds (because it is the first), but the rest of them fail because such a value already exists in the table.
I suggest you switch to a sequence, e.g.
create sequence seq_baby;
and then, in your form, do
select seq_baby.nextval into newmofid from dual;
Got a table, which has a key on itself:
+----+-----------+-----------+
+ ID + ID_PARENT + IS_PARENT +
+----+-----------+-----------+
+ 1 + (null) + 0 +
+ 2 + (null) + 1 +
+ 3 + 2 + 0 +
+----+-----------+-----------+
As you see, ID 1 is on its own, 3 is a child of 2.
Now I want to have a trigger, that on INSERT/UPDATE ...
errors, if an inserted row is it's own parent (not possible)
if it has an ID_PARENT, set the parent's IS_PARENT to 1
This is my approach:
CREATE OR REPLACE TRIGGER tri_table_set_parent
BEFORE
INSERT OR UPDATE ON table
FOR EACH ROW
WHEN ( new.id_parent IS NOT NULL )
BEGIN
IF :new.id = :new.id_parent
THEN
RAISE_APPLICATION_ERROR(-20666, 'A gap cant be the parent of itself. More information here: https://youtu.be/hqRZFWE1X_A');
END IF;
UPDATE table
SET is_parent = 1
WHERE id = :new.id_parent;
END;
/
The error works as intended, woohoo! But now when inserting, I have problems.
When inserting a row without ID_PARENT, it works (because trigger won't trigger at all).
Inserting a row, whose parent's ID_PARENT = (null):
INSERT INTO table (ID, ID_PARENT) VALUES (4, 1);
-> Works!
But inserting a row, whose parent got an ID_PARENT:
INSERT INTO table (ID, ID_PARENT) VALUES (5, 3);
-> Errors:
ORA-04091: Tabelle TABLE wird gerade geändert, Trigger/Funktion sieht dies möglicherweise nicht
ORA-06512: in "TRI_TABLE_SET_PARENT", Zeile 6
ORA-04088: Fehler bei der Ausführung von Trigger "TRI_TABLE_SET_PARENT"
ORA-06512: in "TRI_TABLE_SET_PARENT", Zeile 6
ORA-04088: Fehler bei der Ausführung von Trigger "TRI_TABLE_SET_PARENT"
Updating the table doesn't work at all, same error.
Ok, so I understand that I can't select stuff that might be changed simultaniously. But I'm updating, and also I'm checking that I don't reference the same rows.
So what am I missing?
The evil thing in relational database is redundancy which you try to introduce.
More correct relational approach would be to define the table without the IS_PARENT column.
select * from my_parent order by id;
ID ID_PARENT
---------- ----------
1
2
3 2
... and add the redundant column in an access view
create view V_MY_PARENT as
select a.ID, a.ID_PARENT,
case when exists (select null from my_parent where ID_PARENT = a.ID) then 1 else 0 end as IS_PARENT
from my_parent a
order by a.ID;
To get all non parents you access the view
select * from V_MY_PARENT
where is_parent = 0;
ID ID_PARENT IS_PARENT
---------- ---------- ----------
1 0
3 2 0
If you want to materialize the redundancy (e.g. for performance reasons) use MATERIALIZED VIEWs.
With this approach you will not end with parents classified as no parents or vice versa, which is quite possible in your design.
The error cause is that you are updating row that you didn't inserted yet.
you could update the data you are inserting using :new keyword.
so the solution will be replacing the update statement with
:new.is_parent := 1
ORA-04091 (table is mutating, trigger may not see it) occurs here because you have a BEFORE trigger defined on "TABLE", and in the body of the trigger you're attempting to update "TABLE". Oracle doesn't allow this as it can lead to a trigger loop (i.e. if this was allowed your program could execute a statement which causes the trigger to fire; within the body of the trigger a statement executes which causes the trigger to fire; within the body of the trigger a statement executes which causes the trigger to fire; within the body of the trigger a statement executes which causes the trigger to fire; within the body of the trigger a statement executes which causes the trigger to fire; etc). So you're not allowed to do this in a BEFORE trigger. The simplest fix is to change the trigger to an AFTER trigger. In other words, change BEFORE INSERT OR UPDATE ON table to AFTER INSERT OR UPDATE ON table. In this particular case it doesn't appear this would be a problem, but I don't know what constraints you have on your table which might make this unacceptable. Give it a try.
Just Replace
UPDATE "table"
SET id_parent = 1
WHERE id = :new.id_parent;
with
if :old.id = :new.id_parent and updating then
:new.id_parent := 1;
end if;
e.g avoid using a DML within the same "table" against ORA-04091.
P.S. being table as a reserved keyword, I replaced with "table".
I have the following PL/SQL Block:
declare
vDayType varchar2(10);
TYPE Holidays is table of varchar2(5);
hd Holidays := Holidays('01.01','15.01','19.01','28.05','04.07','08.10','11.11','22.11','25.12');
begin
for s in (select distinct saleDate from Sales) loop
vDayType := case when TO_CHAR(s.saleDate, 'dd.mm') member of hd then
'Holiday'
when to_char(s.saleDate, 'd') IN (1,7) then
'Weekend'
else
'Weekday'
end;
insert into times (saleDay, dayType) values (s.saleDate, vDayType);
end loop;
end;
/
This pulls data from a OLTP Table named SALES and inserts it into the dimension table named TIMES. It incorporates a CASE statement to "calculate" days that are Holidays, Weekdays, or Weekends. Unfortunately, when I run this code, I'm getting the following error:
ERROR at line 1:
ORA-01400: cannot insert NULL into ("CM420A01"."TIMES"."SALEDAY")
ORA-06512: at line 14
I believe it is inserting NULL because I have it set to only SELECT DISTINCT values from saleDate in the SALES OLTP Table. I'm assuming it's still trying to insert the dayType from the CASE statement, even when it's not inserting a saleDay because of the DISTINCT statement, which is thus inserting NULL into the saleDay column and causing the error.
Any tips/tricks to recover from this issue so it'll run without error?
Added WHERE SALES.vehicleStatus = 'sold' clause due to NULL values that were being inserted for vehicles what were listed as pending or available and didn't yet have saleDate's......
I have an application that uses the Oracle MERGE INTO... DML statement to update table A to correspond with some of the changes in another table B (table A is a summary of selected parts of table B along with some other info). In a typical merge operation, 5-6 rows (out of 10's of thousands) might be inserted in table B and 2-3 rows updated.
It turns out that the application is to be deployed in an environment that has a security policy on the target tables. The MERGE INTO... statement can't be used with these tables (ORA-28132: Merge into syntax does not support security policies)
So we have to change the MERGE INTO... logic to use regular inserts and updates instead. Is this a problem anyone else has run into? Is there a best-practice pattern for converting the WHEN MATCHED/WHEN NOT MATCHED logic in the merge statement into INSERT and UPDATE statements? The merge is within a stored procedure, so it's fine for the solution to use PL/SQL in addition to the DML if that is required.
Another way to do this (other than Merge) would be using two sql statements one for insert and one for update. The "WHEN MATCHED" and "WHEN NOT MATCHED" can be handled using joins or "in" Clause.
If you decide to take the below approach, it is better to run the update first (sine it only runs for the matching records) and then insert the non-Matching records. The Data sets would be the same either way, it just updates less number of records with the order below.
Also, Similar to the Merge, this update statement updates the Name Column even if the names in Source and Target match. If you dont want that, add that condition to the where as well.
create table src_table(
id number primary key,
name varchar2(20) not null
);
create table tgt_table(
id number primary key,
name varchar2(20) not null
);
insert into src_table values (1, 'abc');
insert into src_table values (2, 'def');
insert into src_table values (3, 'ghi');
insert into tgt_table values (1, 'abc');
insert into tgt_table values (2,'xyz');
SQL> select * from Src_Table;
ID NAME
---------- --------------------
1 abc
2 def
3 ghi
SQL> select * from Tgt_Table;
ID NAME
---------- --------------------
2 xyz
1 abc
Update tgt_Table tgt
set Tgt.Name =
(select Src.Name
from Src_Table Src
where Src.id = Tgt.id
);
2 rows updated. --Notice that ID 1 is updated even though value did not change
select * from Tgt_Table;
ID NAME
----- --------------------
2 def
1 abc
insert into tgt_Table
select src.*
from Src_Table src,
tgt_Table tgt
where src.id = tgt.id(+)
and tgt.id is null;
1 row created.
SQL> select * from tgt_Table;
ID NAME
---------- --------------------
2 def
1 abc
3 ghi
commit;
There could be better ways to do this, but this seems simple and SQL-oriented. If the Data set is Large, then a PL/SQL solution won't be as performant.
There are at least two options I can think of aside from digging into the security policy, which I don't know much about.
Process the records to merge row by row. Attempt to do the update, if it fails to update then insert, or vise versa, depending on whether you expect most records to need updating or inserting (ie optimize for the most common case that will reduce the number of SQL statements fired), eg:
begin
for row in (select ... from source_table) loop
update table_to_be_merged
if sql%rowcount = 0 then -- no row matched, so need to insert
insert ...
end if;
end loop;
end;
Another option may be to bulk collect the records you want to merge into an array, and then attempted to bulk insert them, catching all the primary key exceptions (I cannot recall the syntax for this right now, but you can get a bulk insert to place all the rows that fail to insert into another array and then process them).
Logically a merge statement has to check for the presence of each records behind the scenes anyway, and I think it is processed quite similarly to the code I posted above. However, merge will always be more efficient than coding it in PLSQL as it will be only 1 SQL call instead of many.