Question

I have a FK inside my table but i want to modify the parent table for the FK . so is there an alter command that can achieve this ? or i need to remove the FK and create a new one ? Thanks

Was it helpful?

Solution

Add this to your PK and it will automatically update all FKs for you:

ON UPDATE CASCADE

For full details, you can read this article.

EDIT Based on your comment, if you want to change the PK data type, it depends on the change:

  • If the old type can be implicitly casted to the new type without any loss:
    1. Change the PK type first.
    2. Change the FK type to the same.
  • If the old type cannot be implicitly casted to the new type without any loss:
    1. Break the relationship first (i.e. remove the FK restriction/index).
    2. Convert the PK. If the data needs to be modified, save both the old values and the new ones in a temporary table.
    3. Convert the FK. If the PK data was changed in previous step, update the FK using the mapped values from the temporary table.
    4. Create the relationship again (i.e. create the FK restriction/index).

To modify the data type, use the ALTER command, the syntax is:

ALTER TABLE table_name
ALTER COLUMN column_name datatype

Examples:

ALTER TABLE table_name
ALTER COLUMN id NUMBER(10,2);

ALTER TABLE table_name
ALTER COLUMN id VARCHAR(20);

For full details, you can read this article.

OTHER TIPS

Looks like you are looking for alter statement but since you didn't mention exactly what you are looking to modify; I assume that you want to change column data type size. You can do something like this (an example; say you want to change size from 10 to 15)

alter table sample3 
alter column name varchar(15)

EDIT:

In that case this is what you should be doing. You need to drop the existing constraint and recreate the constraint to point to TableC

alter table TableA
drop constraint your_FK_constraint_name

alter table TableA
add constraint constraint_name 
FOREIGN KEY (column_name) references TableC(some other column name)

An Example:

alter table sample2
drop constraint FK__sample2__realnam__09DE7BCC

alter table sample2
add constraint FK__sample2__realnam 
FOREIGN KEY (realname) references sample1(name)

Based on this comment, "now my current FK inside TableA is referring to another table primary key TableB. but i need my modify my current FK to refer to tableC instead of tableB ... this what i need (to modify the parent table for my FK)– "

The parent table is TableB. No action is required on that table.

On TableA, you have to:

  1. Drop the existing foreign key constraint.
  2. Update as necessary so that all values in the applicable column have a matching value in TableC.
  3. Add a new foreign key constraint.

in that order.

Edit Starts Here

Here is a link to the syntax,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top