Oracle - Foreign Key references different tables different schemas - oracle

I have problem with Enforcing Referential Integrity to a new table.
There are different tables in different schemas, each one has its primary key:
schema1.table1
schema2.table2
schema3.table3
I want to create a new table, which among other information and its primary id, has a column "reference_schema" and a column "reference_id".
I want the column "referencing id" to reference the id on the relevant table, that is of the "reference_schema"="schema1" to reference the primary key schema1.table1.id.
The primary keys on the 3 tables, aren't unique in a UNION.
I have tried synthesizing a primary key in a UNION ALL view, but Oracle does not enforce view constraints.

It is not the different schema that causes problems, but the fact that you can't create a foreign key constraint which would reference two (or more) different tables.
I mean, you can do it, using out-of-line constraint syntax, but that just won't work. Why? Because - if that value doesn't exist in all referenced tables, constraint will be violated.
create table new_table
(id number constraint pk_newtab primary key,
ref_schema varchar2(30),
ref_id number,
--
constraint fk_newtab_s1 foreign key (ref_id) references schema1.table1 (id),
constraint fk_newtab_s2 foreign key (ref_id) references schema2.table2 (id)
);
A simple example is Scott's sample schema (there is department number 10, but no employee has that EMPNO):
SQL> create table test
2 (id number,
3 constraint fk1 foreign key (id) references scott.dept (deptno),
4 constraint fk2 foreign key (id) references scott.emp (empno)
5 );
Table created.
SQL> insert into test (id) values (10);
insert into test (id) values (10)
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.FK2) violated - parent key not found
SQL>
So, what can you do? Use a trigger. Something like this:
SQL> create or replace trigger trg_test
2 before insert or update on test
3 for each row
4 declare
5 l_cnt number;
6 begin
7 select deptno into l_cnt
8 from dept
9 where deptno = :new.id;
10
11 exception
12 when no_data_found then
13 begin
14 select empno into l_cnt
15 from emp
16 where empno = :new.id;
17
18 exception
19 when no_data_found then
20 raise_application_error(-20000, 'Foreign key does not exist in any referenced table');
21 end;
22 end;
23 /
Trigger created.
Testing:
SQL> insert into test (id) values (10); --> this is ACCOUNTING
1 row created.
SQL> insert into test (id) values (7369); --> this is SMITH
1 row created.
SQL> insert into test (id) values (99); --> this doesn't exist in any table
insert into test (id) values (99)
*
ERROR at line 1:
ORA-20000: Foreign key does not exist in any referenced table
ORA-06512: at "SCOTT.TRG_TEST", line 17
ORA-04088: error during execution of trigger 'SCOTT.TRG_TEST'
SQL>

From Oracle 12, you can use virtual columns and put the constraints on the virtual column.
For example, if you have the tables:
CREATE TABLE table1 (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);
CREATE TABLE table2 (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);
CREATE TABLE table3 (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);
Then you can create your table as:
CREATE TABLE new_table(
id NUMBER
GENERATED ALWAYS AS IDENTITY
PRIMARY KEY,
reference_table VARCHAR2(30)
CHECK (reference_table IN ('table1', 'table2', 'table3')),
reference_id NUMBER
NOT NULL,
t1_id NUMBER
INVISIBLE
AS (
CASE reference_table WHEN 'table1' THEN reference_id END
)
REFERENCES table1(id),
t2_id NUMBER
INVISIBLE
AS (
CASE reference_table WHEN 'table2' THEN reference_id END
)
REFERENCES table2(id),
t3_id NUMBER
INVISIBLE
AS (
CASE reference_table WHEN 'table3' THEN reference_id END
)
REFERENCES table3(id)
);
Note: If you want to change from different tables in the same schema to the same table in different schemas then just update the foreign key constraint to point to the correct location.
db<>fiddle here

Related

I cannot display the values of the 2 table Ceremony and Referee

create table STADIUM
( stad_location varchar2(20) primary key
, stad_name varchar2(10)
, stad_capacity number(5)
, match_ID char(8)
, stall_ID char(4)
, foreign key (match_ID) references MATCH (match_ID) ON DELETE SET NULL
, foreign key (stall_ID) references STALL (stall_ID) ON DELETE SET NULL);
create table TRANSPORTATION
(registra_no char(6) primary key
, transp_type varchar2(10)
, capacity number(2)
);
create table CEREMONY
(cerem_type varchar2(10) primary key
, cerem_name varchar2(15)
, FIFA_theme_song varchar2(20)
, p_ID char(8)
, stad_location varchar2(20)
, foreign key (p_ID) references PERFORMER(p_ID) ON DELETE SET NULL
, foreign key (stad_location) references STADIUM(stad_location)ON DELETE SET NULL
);
create table REFEREE( ref_ID char(8) primary key
, ref_name varchar2(20)
, yo_exp number(2)
, match_ID char(8)
, registra_no char(6)
, foreign key (match_ID) references MATCH (match_ID) ON DELETE SET NULL
, foreign Key (registra_no) references TRANSPORTATION(registra_no) ON DELETE SET NULL);
insert into CEREMONY values('Opening', 'Speech', 'Colors', 'PP561475', 'Al-Waab Street');
insert into REFEREE values('RF503624','Mike Dean', 25, 'MM129456', 'QLM729'); select * from CEREMONY;
select * from REFEREE;
Bunch of tables are missing, referenced by foreign keys so I'm creating them first:
SQL> -- Missing tables, referenced by foreign keys
SQL> create table match (match_id char(8) primary key);
Table created.
SQL> create table stall (stall_id char(4) primary key);
Table created.
SQL> create table performer (p_id char(8) primary key);
Table created.
SQL>
Your tables:
SQL> create table STADIUM
2 ( stad_location varchar2(20) primary key
3 , stad_name varchar2(10)
4 , stad_capacity number(5)
5 , match_ID char(8)
6 , stall_ID char(4)
7 , foreign key (match_ID) references MATCH (match_ID) ON DELETE SET NULL
8 , foreign key (stall_ID) references STALL (stall_ID) ON DELETE SET NULL);
Table created.
SQL> create table TRANSPORTATION
2 (registra_no char(6) primary key
3 , transp_type varchar2(10)
4 , capacity number(2)
5 );
Table created.
SQL> create table CEREMONY
2 (cerem_type varchar2(10) primary key
3 , cerem_name varchar2(15)
4 , FIFA_theme_song varchar2(20)
5 , p_ID char(8)
6 , stad_location varchar2(20)
7 , foreign key (p_ID) references PERFORMER(p_ID) ON DELETE SET NULL
8 , foreign key (stad_location) references STADIUM(stad_location)ON DELETE SET NULL
9 );
Table created.
SQL> create table REFEREE( ref_ID char(8) primary key
2 , ref_name varchar2(20)
3 , yo_exp number(2)
4 , match_ID char(8)
5 , registra_no char(6)
6 , foreign key (match_ID) references MATCH (match_ID) ON DELETE SET NULL
7 , foreign Key (registra_no) references TRANSPORTATION(registra_no) ON DELETE SET NULL);
Table created.
SQL>
Inserts into tables referenced by ceremony and referee:
SQL> insert into performer values ('PP561475');
1 row created.
SQL> insert into stadium (stad_location) values ('Al-Waab Street');
1 row created.
SQL> insert into match values ('MM129456');
1 row created.
SQL> insert into transportation (registra_no) values ('QLM729');
1 row created.
SQL>
Your inserts & result of your select statements:
SQL> insert into CEREMONY values('Opening', 'Speech', 'Colors', 'PP561475', 'Al-Waab Street');
1 row created.
SQL> insert into REFEREE values('RF503624','Mike Dean', 25, 'MM129456', 'QLM729');
1 row created.
SQL> select * from CEREMONY;
CEREM_TYPE CEREM_NAME FIFA_THEME_SONG P_ID STAD_LOCATION
---------- --------------- -------------------- -------- --------------------
Opening Speech Colors PP561475 Al-Waab Street
SQL> select * from REFEREE;
REF_ID REF_NAME YO_EXP MATCH_ID REGIST
-------- -------------------- ---------- -------- ------
RF503624 Mike Dean 25 MM129456 QLM729
SQL>
Therefore, if you do everything right, everything is right.

How to change column identify from sequence to GENERATED ALWAYS with data

as my title, I want to change my identity column by sequence to GENERATED ALWAYS.
For ex, I have a table like this:
CREATE SEQUENCE DPT.Deposit_SEQ
START WITH 1
INCREMENT BY 10
NOCACHE
NOCYCLE;
CREATE TABLE DPT.TEST(
Id NUMBER(10)DEFAULT DPT.Deposit_SEQ.nextval NOT NULL
,Code VARCHAR2(20),
CONSTRAINT PK_TEST PRIMARY KEY (ID)
);
Insert into DPT.TEST (ID, CODE) values (1,'ABC');
COMMIT;
Now, I want to change from sequence to GENERATED ALWAYS like this:
Id NUMBER(10) GENERATED ALWAYS AS IDENTITY START WITH 6
INCREMENT BY 10
NOCACHE
NOCYCLE;
I tried by create one more column and drop old column but failed. How can I do that?
Thanks!
"But failed" is not an Oracle error and is difficult to debug.
Anyway, it works for me:
Create table and a sequence, insert some rows:
SQL> CREATE SEQUENCE Deposit_SEQ START WITH 1 INCREMENT BY 10 NOCACHE NOCYCLE;
Sequence created.
SQL> CREATE TABLE TEST
2 (
3 Id NUMBER (10) DEFAULT Deposit_SEQ.NEXTVAL NOT NULL,
4 Code VARCHAR2 (20),
5 CONSTRAINT PK_TEST PRIMARY KEY (ID)
6 );
Table created.
SQL>
SQL> INSERT INTO TEST (ID, CODE)
2 VALUES (1, 'ABC');
1 row created.
SQL> INSERT INTO TEST (ID, CODE)
2 VALUES (3, 'DEF');
1 row created.
SQL> SELECT * FROM test;
ID CODE
---------- --------------------
1 ABC
3 DEF
Drop current primary key column (ID) and add a new, identity column:
SQL> ALTER TABLE test
2 DROP COLUMN id;
Table altered.
SQL> ALTER TABLE test
2 ADD id NUMBER GENERATED ALWAYS AS IDENTITY START WITH 6;
Table altered.
SQL> SELECT * FROM test;
CODE ID
-------------------- ----------
ABC 6
DEF 7
SQL> ALTER TABLE test ADD CONSTRAINT pk_test PRIMARY KEY (id);
Table altered.
SQL>
As you can see, no problem.

cannot insert data into the 4th table

I used the following script to create 4 test tables: dept1, dept2, dept3, and dept4. The code is exactly the same for each table. All tables are created successfully but the insert into statements only worked for the first three tables. After dropping all tables and purge the recyclebin, I moved Create Table dept4 and the following insert into statements to the top of the code. Then the insert into statement does not work for Dept3. Basically, I can only insert data into the first three tables in the script and not able to insert data into the 4th table on the script.
The error message is the following:
SQL Error: ORA-00604: error occurred at recursive SQL level 1
ORA-30667: cannot drop NOT NULL constraint on a DEFAULT ON NULL column
00604. 00000 - "error occurred at recursive SQL level %s"
This happened after some users created identity columns in Oracle 12.1 database. Some users used:
GENERATED ALWAYS AS IDENTITY
Other users used:
GENERATED BY DEFAULT ON NULL AS IDENTITY
Code used:
CREATE TABLE DEPT1 (
DEPT1NO NUMBER(2) NOT NULL,
DNAME VARCHAR2(14),
LOC VARCHAR2(13),
CONSTRAINT DEPT1_PRIMARY_KEY PRIMARY KEY (DEPT1NO));
INSERT INTO DEPT1 VALUES (10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT1 VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT1 VALUES (30,'SALES','CHICAGO');
INSERT INTO DEPT1 VALUES (40,'OPERATIONS','BOSTON');
CREATE TABLE DEPT2 (
DEPT2NO NUMBER(2) NOT NULL,
DNAME VARCHAR2(14),
LOC VARCHAR2(13),
CONSTRAINT DEPT2_PRIMARY_KEY PRIMARY KEY (DEPT2NO));
INSERT INTO DEPT2 VALUES (10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT2 VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT2 VALUES (30,'SALES','CHICAGO');
INSERT INTO DEPT2 VALUES (40,'OPERATIONS','BOSTON');
CREATE TABLE DEPT3 (
DEPT3NO NUMBER(2) NOT NULL,
DNAME VARCHAR2(14),
LOC VARCHAR2(13),
CONSTRAINT DEPT3_PRIMARY_KEY PRIMARY KEY (DEPT3NO));
INSERT INTO DEPT3 VALUES (10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT3 VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT3 VALUES (30,'SALES','CHICAGO');
INSERT INTO DEPT3 VALUES (40,'OPERATIONS','BOSTON');
CREATE TABLE DEPT4 (
DEPT4NO NUMBER(2) NOT NULL,
DNAME VARCHAR2(14),
LOC VARCHAR2(13),
CONSTRAINT DEPT4_PRIMARY_KEY PRIMARY KEY (DEPT4NO));
INSERT INTO DEPT4 VALUES (10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT4 VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT4 VALUES (30,'SALES','CHICAGO');
INSERT INTO DEPT4 VALUES (40,'OPERATIONS','BOSTON');

parent keys not found Oracle 10g

I have two tables :
SQL> desc SEGMENT
Name Null? Type
----------------------------------------- -------- ----------------------------
INDIP NOT NULL VARCHAR2(11)
NOMSEGMENT NOT NULL VARCHAR2(20)
ETAGE
SQL> desc POSTE
Name Null? Type
----------------------------------------- -------- ----------------------------
NPOSTE NOT NULL VARCHAR2(7)
NOMPOSTE NOT NULL VARCHAR2(20)
INDIP VARCHAR2(11)
AD VARCHAR2(3)
TYPEPOSTE VARCHAR2(9)
NSALLE VARCHAR2(7)
I want to add a constraint as the following :
ALTER TABLE "POSTE" ADD CONSTRAINT "FK_POSTE_SEGMENT" FOREIGN KEY ("INDIP") REFERENCES "SEGMENT" ("INDIP") ENABLE;
But I got this error message :
ERROR at line 1: ORA-02298: cannot validate (AIMAD.FK_POSTE_SEGMENT) -
parent keys not found
How can I solve this
You should check what POSTE table does not contain values in INDIP column what don't exist in INDIP column of SEGMENT table.
Like
SQL> create table t (x int primary key);
SQL> insert into t values(1);
SQL> create table t_c (x int);
SQL> insert into t_c values(1);
SQL> insert into t_c values(2);
SQL> commit;
SQL> alter table t_c add constraint t_c_x foreign key(x)
2 references t(x);
alter table t_c add constraint t_c_x foreign key(x)
*
ORA-02298: cannot validate (SCOTT.T_C_X) - parent key not found
SQL> select * from t_c where not exists (select *
2 from t where t.x = t_c.x);
X
-----------------------
2
Also Oracle provides the ability to create constraint in NOVALIDATE status, this prevents Oracle from checking data during contraint creation:
SQL> alter table t_c add constraint t_c_x foreign key(x)
2 references t(x) enable novalidate;
Table altered.
but this can have undesirable side effects because data in both tables are not consistent.

Copy or show the primary key value into another table as foreign key APEX

I have two tables A and B .i want to copy or show the primary key column value from table A in the foreign key column in table B respectively .is there any method kindly help me.
Regards,
You can populate your primary key value while populating table B or by using a trigger when you are populating table A.
CREATE TABLE t1 (id1 NUMBER, dt DATE);
ALTER TABLE t1 ADD (
CONSTRAINT t1_pk
PRIMARY KEY
(id1));
CREATE TABLE t2 (id2 NUMBER, id1 NUMBER, dt2 DATE);
ALTER TABLE t2 ADD (
CONSTRAINT t2_pk
PRIMARY KEY
(id2));
ALTER TABLE t2
ADD CONSTRAINT t2_r01
FOREIGN KEY (id2)
REFERENCES t1 (id1);
First Approach, by this way you could populate second table when you are inserting values.
INSERT INTO t1
VALUES (1, SYSDATE
);
INSERT INTO t2
VALUES (1, 1, SYSDATE
);
With trigger, so when values are inserted into first table second tables values are populated using a trigger. So primary key value of first table is being inserted into foreign key of table 2.
CREATE OR REPLACE TRIGGER my_trigger
AFTER INSERT
ON t1
FOR EACH ROW
BEGIN
INSERT INTO t2
VALUES (1, :new.id1, SYSDATE
);
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;

Resources