Replacing Primary Key PL SQL - oracle

I am trying to write a PL/SQL procedure that will look for an existing primary key "supplier_id" from the supplier table and replacing it with a new one. The primary key "supplier_id" is also a foreign key for a few other tables. Therefore I need update the foreign key locations as well. Here is the procedure I have written to solve this:
create or replace PROCEDURE ex5b_supplier_update(supplier_id_delete IN VARCHAR2,
supplier_id_update IN VARCHAR2) IS
CURSOR supplier_cursor IS
SELECT supplier_id
FROM supplier;
supplier_row supplier_cursor%rowtype;
BEGIN
OPEN supplier_cursor;
LOOP
FETCH supplier_cursor INTO supplier_row;
EXIT WHEN supplier_cursor%notfound;
IF ex5b_supplier_exist(supplier_id_delete) THEN
UPDATE supplier
SET supplier_id = supplier_id_update
WHERE supplier_id = supplier_id_delete;
UPDATE PURCHASE_ORDER
SET supplier_id = supplier_id_update
WHERE supplier_id = supplier_id_delete;
UPDATE PRODUCT
SET supplier_id = supplier_id_update
WHERE supplier_id = supplier_id_delete;
DBMS_OUTPUT.PUT_LINE('UPDATED');
ELSE
DBMS_OUTPUT.PUT_LINE('NOT UPDATED');
END IF;
END LOOP;
CLOSE supplier_cursor;
END;
The procedure gives me the following error:
Error starting at line : 2 in command -
BEGIN
ex5b_supplier_update('S500','S600');
END;
Error report - ORA-02292: integrity constraint (SYSTEM.PRODUCT_FK)
violated - child record found ORA-06512: at
"SYSTEM.EX5B_SUPPLIER_UPDATE", line 15 ORA-06512: at line 2
02292. 00000 - "integrity constraint (%s.%s) violated - child record found"
*Cause: attempted to delete a parent key value that had a foreign
dependency.
*Action: delete dependencies first then parent or disable constraint.
Which makes total sense you cannot delete a primary key that is used as a foreign key. But I also can't change foreign keys that have no primary keys.
So my question is how can I change the supplier_id and all its foreign keys at the same time to avoid this error?

In a relational database a primary key is guaranteed to be three things:
1) Not nullable
2) Unique
3) UNCHANGING
It's the third rule which you're violating here, and from the errors you're getting perhaps you see why. This way lies madness. Do not change the value of a primary key. Change the attribute values all you like, so that the row now appears to be something completely different - but do not change the primary key. If you need think you need to change the primary key what you're really saying is that your primary key is not, in fact, primary. It might be a unique key, but it is by definition not a primary key.
Primary keys do not get changed.
Best of luck.
EDIT
If you really want to "change" the primary key without disabling constraints and etc, here's what you do:
Start a transaction.
Create a new row in your table with a new ID.
Copy all attributes EXCEPT FOR THE PRIMARY KEY ID COLUMN from the "original" row to the "new" row.
Update all rows in tables with foreign key constraints which reference the "original" row to reference the "new" row, i.e. change the "old" ID value to the "new" ID value.
Delete the "original" row.
COMMIT the transaction.
When done in this manner you don't violate any of the rules regarding primary keys, and at the end of the transaction the primary key appears to have been changed and all FK's are updated.
Best of luck.

Related

How to capture constraint name using save exception in PL/SQL?

I need to perform delete in bulk from multiple tables.
These tables are having referential integrity constraint enabled.
In case if I miss out to delete any record from child table, I should be able to capture the foreign key constraint name that got violated.
I'm able to capture the foreign key constraint name if I don't use SAVE EXCEPTIONS, however if I use SAVE EXCEPTIONS I'm not able to capture the name.
e.g. To demonstrate I have created 2 tables with referential integrity.
test_parent(id number,PARENT_NAME VARCHAR2)
test_child (id number,child_NAME VARCHAR2)
id column is referenced from test_child to test_parent
I inserted few records in both and then tried to delete from test_parent without deleting from test_child to replicate the error for demonstration.
set serveroutput on <br>
declare <br>
cursor cp is select * from test_parent;<br>
type t_cp is table of cp%rowtype;<br>
tt_cp t_cp;<br>
begin<br>
select * bulk collect into tt_cp from test_parent;<br>
begin<br>
forall idx in 1..tt_cp.count save exceptions<br>
delete from TEST_PARENT where id=tt_cp(idx).id;<br>
exception<br>
when others then<br>
for i in 1..sql%bulk_exceptions.count<br>
loop<br>
dbms_output.put_line(sqlerrm(-1 * SQL%BULK_EXCEPTIONS(i).ERROR_CODE));<br>
end loop;<br>
end;<br>
exception<br>
when others then<br>
rollback;<br>
dbms_output.put_line(sqlerrm);<br>
rollback;<br>
end;<br>
/<br>
How do I capture the constraint name along with using SAVE EXCEPTIONS?
[Below output if I don't use SAVE EXCEPTIONS]
ORA-02292: integrity constraint (SYSTEM.SYS_C0014790) violated - child record found
[Below output if I use SAVE EXCEPTIONS]
ORA-02292: integrity constraint (.) violated - child record found
ORA-02292: integrity constraint (.) violated - child record found

How i can solve ORACLE problem in foreign key

I have a problem in oracle and I need help. I have the following query:
1 CREATE TABLE TEST1 (
2 NAME VARCHAR(20)
3 ID VAR(9)
4 PRIMARY KEY(ID)
5 FOREIGN KEY(NAME) References TEST2(ANAME)
6 ON DELETE CASCADE ON UPDATE SET NULL );
If I want to delete line #6 what should i do?
"How I can change the value of primary key and based of that the foreign keys of this pk will change too?"
First, you should never need to do that. Primary keys like this are really just numbers that identify a row, they have no meaning in themselves. It's like asking how you would change the ROWID of a row.
If you must, you could:
Find the foreign keys pointing to this table and disable them with ALTER CONSTRAINT myconstraint DISABLE
Update your primary table and catch the new id value with UPDATE test1 SET id = mysequence.NEXTVAL WHERE id = :oldid RETURNING id INTO :newid, assuming it's set by a sequence.
Update the ids in your other tables with the new id.
Reenable your constraints.
Note that altering constraints is DDL and will do an implicit commit and this approach will leave your tables unprotected by the foreign key constraints.
A second approach would be to:
Insert a new row in the primary table and catch the new id.
Update the id in the foreign tables with the new id.
Delete the old row in the primary table.
Now that I think about it, that second approach seems better to me. No DDL and it just seems cleaner.

Foreign Keys or Delete Trigger?

The tables:
SIGN_OBJECT:
ID VARCHAR2(32) PRIMARY KEY,
DESCRIPTION VARCHAR2(100),
X NUMBER(10,3),
Y NUMBER(10,3),
...
GEOMETRYID VARCHAR2(32)
LAMPPOST_OBJECT:
ID VARCHAR2(32) PRIMARY KEY,
DESCRIPTION VARCHAR2(100),
X NUMBER(10,3),
Y NUMBER(10,3),
...
GEOMETRYID VARCHAR2(32)
OBJGEOMETRY:
GEOMETRYID VARCHAR2(32) PRIMARY KEY,
GEOMETRY MDSYS.SDO_GEOMETRY,
...
There are many X_OBJECT tables. Unfortunately the schema designers (in their infinite wisdom) didn't see any crossover between the various object types. I am unable to change these tables without creating much more work.
For each object table there is a trigger that creates the relevant SDO_GEOMETRY value BEFORE insert or update ( GEOMETRYID is unique - it comes from a sequence ). At the moment the trigger calls a package function which inserts the OBJGEOMETRY record and returns the geometryid.
The problem is that if the parent record is deleted I would like the OBJGEOMETRY child record to be also deleted.
Initially I thought this could be done with Foreign Keys cascade delete, but of course the FK requires a Primary Key in the parent table - obviously this won't work.
However, I discovered that actually a FK requires a unique constraint in the parent table. I can make X_OBJECT.GEOMETRYID unique but then I'm finding issues because that GEOMETRYID isn't yet populated in the parent table but the FK requires it exists. I cannot do that inside the trigger ( by setting :NEW.GEOMETRYID ) so do I have to write the GEOMETRYID first and then commit? I'm not sure and this has bad code smell.
So am I wrong? Is this a more suitable case for a delete trigger? or is there something I'm missing.
Thanks.
If you insert both the OBJGEOMETRY and the X_OBJECT rows in the same transaction, then you can set the FK to DEFERRABLE INITIALLY DEFERRED.
In that case it will be evaluated at COMMIT time, not when you run the INSERT statement.
The triggers should fire before insert or update, not after. Then you can set :NEW.GEOMETRYID with the value returned by your package.
Besides, the foreign keys point the wrong way. It should be
ALTER TABLE x_OBJECT ADD FOREIGN KEY (geometryid) REFERENCES objgeometry(geometryid);
Therefore, you'll need a delete trigger...

Oracle Database with very few foreign key constraints

I've just started a new project and I am confronted with a production application Oracle 10g database that has just 3 foreign key constraints. I am not used to seeing databases with no foreign key constraints. I am guessing that there may be some performance/concurrency considerations to not using FKs. The reason is that in the logical database schema the architect has specified all the relationships, but these relationships are not implemented in the database as Foreign Key constraints.
Question: I read that I can define a Foreign Key Constraint with RELY NOVALIDATE that will not impact performance. Is it worth while to define RELY FK constraints on this database just so that the relationship can be easily seen? this application is not built using ORM, is it really worth while to do without foreign keys?
The database is denormalised with example below
Table 1 : FINProduct(ID (number), Description(varchar(5)), FINproductCode(varchar(10))...)
Table 2: FINProductCode(ID (number, FINproductCode(varchar(10)) , LastUpdated(datetime)...)
So instead of having a relationship between Tables 1 and 2 the FINproductCode column is just replicated in table 1.
It's too early to drink but I think i need one!
I would be very wary about assuming that the absence of foreign key constraints was a reasoned response to performance issues. There is an overhead to enforcing a foreign key constraint (particularly where appropriate indexes are missing) but it is incredibly unlikely that your application can validate the constraint more efficiently than Oracle can. So the question really is whether you want the small overhead of foreign key constraints or the near certainty that you will get invalid data inserted into the database. It would be extremely unlikely that this is a trade-off that you want to make-- I've yet to meet a business user that would be happy to capture incorrect and incomprehensible data even if doing so was a bit faster than capturing correct data.
Unless there is substantially more background, I would tend to create all the missing foreign key constraints. Creating RELY NOVALIDATE constraints is possible but it defeats the major benefit of foreign key constraints-- preventing invalid data from entering the database in the first place.
It depends on whether you want to add the FK only for documentation purposes or whether you want to prevent future INSERTs/UPDATEs with an invalid FK value.
If you want it only for documentation purposes, I'd create the FK constraint with RELY NOVALIDATE and DISABLE it afterwards - otherwise, Oracle will check it for future INSERTs / UPDATEs.
However: DON'T DO THIS UNLESS YOU ABSOLUTELY NEED IT!
I agree with Justin Cave: In most cases, you should just add "plain" FK constraints - this way, you can ensure that your existing data is correct.
I would try to create the constraints and report violations into a exception table. Fix the data and enable the constraint.
Create some test data
create table parent (pk integer
,data varchar2(1)
,CONSTRAINT PARENT_PK PRIMARY KEY (PK) ENABLE );
create table child (pk integer
,pk_parent integer
,data varchar2(1)
,CONSTRAINT CHILD_PK PRIMARY KEY (PK) ENABLE );
insert into parent values (1,'a');
insert into parent values (2,'b');
insert into child values (1,1,'a');
insert into child values (2,2,'b');
insert into child values (3,3,'c');
Create a foreign key constraint:
alter table child add constraint fk_parent foreign key(pk_parent) references parent(pk);
SQL Error: ORA-02298: Kan (ROB.FK_PARENT) niet valideren - bovenliggende sleutels zijn niet gevonden.
02298. 00000 - "cannot validate (%s.%s) - parent keys not found"
*Cause: an alter table validating constraint failed because the table has
child records.
*Action: Obvious
Create the foreign key with 'enable novalidate' option
alter table child add constraint fk_parent foreign key(pk_parent) references parent(pk) enable novalidate;
table CHILD altered.
insert into child values (4,4,'c');
SQL Error: ORA-02291: Integriteitsbeperking (ROB.FK_PARENT) is geschonden - bovenliggende sleutel is niet gevonden.
02291. 00000 - "integrity constraint (%s.%s) violated - parent key not found"
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.
No new data violating the FK can be inserted.
Now let's fix the data already in the table that violates the FK constraint
Create an exceptions table and try to enable the constraint:
create table exceptions(row_id rowid,
owner varchar2(30),
table_name varchar2(30),
constraint varchar2(30));
ALTER TABLE child ENABLE constraint fk_parent EXCEPTIONS INTO EXCEPTIONS;
Error report:
SQL Error: ORA-02298: Kan (ROB.FK_PARENT) niet valideren - bovenliggende sleutels zijn niet gevonden.
02298. 00000 - "cannot validate (%s.%s) - parent keys not found"
*Cause: an alter table validating constraint failed because the table has
child records.
*Action: Obvious
Check the exceptions table for problems:
select * from exceptions;
ROW_ID OWNER TABLE_NAME CONSTRAINT
------ ------------------------------ ------------------------------ ------------------------------
AABA78 ROB CHILD FK_PARENT
AAFAAA
Ow9AAC
select * from child where rowid = 'AABA78AAFAAAOw9AAC';
Fix the problem
delete from child where pk = 3;
1 rows deleted.
ALTER TABLE child ENABLE constraint fk_parent EXCEPTIONS INTO EXCEPTIONS;
table CHILD altered.
Constraint enabled and data correct

does foreign key always reference to a unique key in another table?

Is it not possible that foreign key(single column) in a child table references to a parent key which has some duplicate values?
By the SQL standard, a foreign key must reference either the primary key or a unique key of the parent table. If the primary key has multiple columns, the foreign key must have the same number and order of columns. Therefore the foreign key references a unique row in the parent table; there can be no duplicates.
Re your comment:
If T.A is a primary key, then no you can't have any duplicates. Any primary key must be unique and non-null. Therefore if the child table has a foreign key referencing the parent's primary key, it must match a non-null, unique value, and therefore references exactly one row in the parent table. In this case you can't make a child row that references multiple parent rows.
You can create a child row whose foreign key column is NULL, in which case it references no row in the parent table.
No, it is not possible.
When you define a foreign key constraint on a table, it means there is only one corresponding key on the foreign table. If multiples existed on the foreign table which one would be meant?
Wikipedia has this definition on the Foreign key entry:
A foreign key is a field in a relational table that matches a candidate key of another table
Candidate keys are unique within a table.
Yes, it is possible for a foreign key to reference a column with duplicate values.
This can happen if the primary key uses a non-unique index and is not validated when it is created. (But I have never seen a situation like this in real life. As #Bill Karwin pointed out, it would be very confusing. So this may not be a situation you really need to worry about.)
--Create a table with two duplicate rows
create table test1(a number);
insert into test1 values(1);
insert into test1 values(1);
commit;
--Create a non-unique index
create index test1_index on test1(a);
--Use the non-unique index for the primary key, do not validate
alter table test1 add constraint test1_pk primary key (a)
using index test1_index novalidate;
--Build another table with a foreign key to TABLE1
create table test2(a number,
constraint test2_fk foreign key (a) references test1(a));
--Inserting a value that refers to the duplicate value still works.
insert into test2 values(1);
commit;
--The foreign key still works:
--ORA-02291: integrity constraint (TEST2_FK) violated - parent key not found
insert into test2 values(2);
--The primary key works as expected, but only for new values:
--ORA-00001: unique constraint (TEST1_PK) violated
insert into test1 values(1);

Resources