简体   繁体   中英

How to drop an inline foreign key in Oracle-SQL using ALTER TABLE?

create table supplier(  
.  
.  
.  
city varchar2(16) references city(city_name)  
);  

What's the correct query?

alter table suppliers modify city varchar2(16);  

The problem you have is that you have created a foreign key without giving a name to the constraint. This is bad practice, because it makes it harder to manipulate the constraint, as pretty much all Oracle DDL requires the object name.

When we don't explicitly name the constraints Oracle generates a default one. These are all horribly similar and there is no way of telling what the constraint actually does. For instance, if you had three foreign key constraints on SUPPLIER you would need to join with the USER_CONS_COLUMNS view in order to see which constraint actually enforce a rule on the CITY column.

So, for future reference,

city varchar2(16) constraint city_fk references city(city_name)

Anyway, right now you need to find the defaulted name of the foreign key constraint, so you can drop it. We'll assume you were equally sloppy with the CITY table, so first we need to find its primary key (you can skip this stage if you actually know the name).

 select constraint_name 
 from user_constraints
 where table_name = 'CITY' 
 and constraint_type = 'P'

Next, feed that name into this query:

 select constraint_name 
 from user_constraints
 where table_name = 'SUPPLIER' 
 and constraint_type = 'R'
 and r_constraint_name = '&CITY_PK'

Finally, drop the constraint:

alter table supplier drop constraint city_fk

You want to do this:

ALTER TABLE supplier
DROP CONSTRAINT constraint_name

If you didn't give the constraint a explicit name, Oracle asigned one for you so you have to find it first. You can list all the table constraints with, eg:

SELECT *
FROM user_constraints
WHERE TABLE_NAME='SUPPLIER'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM