Удалить foreign key oracle

Обновлено: 07.07.2024

Команда FOREIGN KEY ограничение - это ключ, используемый для связывания двух таблиц вместе.

Внешний ключ - это поле (или набор полей) в одной таблице, которое ссылается на первичный ключ в другой таблице.

SQL FOREIGN KEY в CREATE TABLE

Следующий SQL создает внешний ключ в столбце "PersonID" при создании таблицы "Orders":

CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

SQL Server / Oracle / MS Access:

CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);

Чтобы разрешить именование ограничения внешнего ключа и определить ограничение внешнего ключа для нескольких столбцов, используйте следующий синтаксис SQL:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

SQL FOREIGN KEY в ALTER TABLE

Чтобы создать ограничение внешнего ключа для столбца "PersonID", когда таблица "Orders" уже создана, используйте следующий SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

Чтобы разрешить именование ограничения внешнего ключа и определить ограничение внешнего ключа для нескольких столбцов, используйте следующий синтаксис SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

Отбрасить ограничение внешнего ключа

Чтобы удалить ограничение внешнего ключа, используйте следующий SQL:

ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;

SQL Server / Oracle / MS Access:

Упражнения

Тесты

КАК СДЕЛАТЬ

ПОДЕЛИТЬСЯ

СЕРТИФИКАТЫ

Сообщить об ошибке

Если вы хотите сообщить об ошибке или сделать предложение, не стесняйтесь, присылайте нам электронное письмо:

Ваше предложение:

Спасибо, за вашу помощь!

Топ Учебники

Топ Справочники

Топ Примеры

Веб Сертификаты

SchoolsW3 оптимизирован для обучения, тестирования и тренировки. Примеры упрощают и улучшают чтение и базовое понимание. Учебники, справочники, примеры постоянно пересматриваются, для того, чтобы избежать ошибки, невозможно гарантировать правильность всего содержимого. Используя данный сайт, вы соглашаетесь прочитать и принять условия использования, cookie и Политика конфиденциальности. Авторское право 1999 - 2021 Все права защищены.
Работает на W3.CSS.

I want to remove foreign key from another table so i can insert values of my choice.

I am new in databases so please tell me correct sql query to drop or remove foreign key value.

96.6k 41 41 gold badges 229 229 silver badges 355 355 bronze badges 2,750 5 5 gold badges 27 27 silver badges 42 42 bronze badges

15 Answers 15

4,343 2 2 gold badges 21 21 silver badges 28 28 bronze badges You can also find the name of the constraint, of course, by typing \d table_name in postgres command line client. Usually looks like "fk. " @Nytux The OP clearly stated that the platform is MS SQL Server, not PostgreSQL (tags and question title).

Its wrong to do that in refer to referential integrity, because once its broken its not easy to turn it on again without having to go through the records and delete the ones which breaks the constraints.

Anyway the Syntax is as follows:

35.7k 70 70 gold badges 93 93 silver badges 127 127 bronze badges No, the syntax in SQL Server for dropping Foreign Key and Primary Key are the same: alter table <tablename> drop constraint <fk_or_pk_name>

To remove all the constraints from the DB:



But, be careful man, once you do that, you may never get a chance back, and you should read some basic database book see why we need foreign key

2,814 1 1 gold badge 14 14 silver badges 32 32 bronze badges

Drop all the foreign keys of a table:

you are wrong with parent_object_id . it should be used instate of that referenced_object_id

You should consider (temporarily) disabling the constraint before you completely delete it.

If you look at the table creation TSQL you will see something like:

. then insert/update a bunch of values that violate the constraint, and then turn it back on by running the original CHECK statement.

(I have had to do this to cleanup poorly designed systems I've inherited in the past.)

2,804 7 7 gold badges 39 39 silver badges 77 77 bronze badges

Depending on the DB you are using there's a syntax or another.

If you're using Oracle you have to put what the other users told you:

But if you use MySQL then this will give you a syntax error, instead you can type:

519 1 1 gold badge 8 8 silver badges 24 24 bronze badges

to see the descriptive structure of your table.

There you may see constraints respective to foreign keys you used in that table. First delete the respective constraint with

and then delete the respective foreign keys or column you wanted. GoodLuck!!

EDIT: didn't notice you were using sql-server, my bad


682 2 2 gold badges 9 9 silver badges 14 14 bronze badges

Use those queries to find all FKs:


10.5k 14 14 gold badges 96 96 silver badges 127 127 bronze badges

Alternatively, you can also delete a Foreign Key Constraint from the SQL Server Management Studio itself. You can try it if the commands do not work.

  1. Expand your database view.
  2. Right Click on Table which has foreign key constraint. Choose Design. A tab with the information about table columns will open.
  3. Right click on the column which has the foreign key reference. Or you can right click on any column. Choose Relationships.
  4. A list of relationships will appear (if you have one) in a pop up window.
  5. From there you can delete the foreign key constraint.

I hope that helps

If you find yourself in a situation where the FK name of a table has been auto-generated and you aren't able to view what it exactly is (in the case of not having rights to a database for instance) you could try something like this:

Build up a stored proc which drops the constraint of the specified table without specifying the actual FK name. It drops the constraint where the object [type] is equal to F (Foreign Key constraint).

Note: if there are multiple FK's in the table it will drop them all. So this solution works best if the table you are targeting has just one FK.


If you don't know foreign key constraint name then try this to find it.

additionally for different schema


To be on the safer side, just name all your constraints and take note of them in the comment section.

This Oracle tutorial explains how to use Foreign Keys with cascade delete in Oracle with syntax and examples.

What is a foreign key with Cascade DELETE in Oracle?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in Oracle.

A foreign key with a cascade delete can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.

Using a CREATE TABLE statement

Syntax

The syntax for creating a foreign key with cascade delete using a CREATE TABLE statement in Oracle/PLSQL is:

Example

Let's look at an example of how to create a foreign key with cascade delete using the CREATE TABLE statement in Oracle/PLSQL.

In this example, we've created a primary key on the supplier table called supplier_pk. It consists of only one field - the supplier_id field. Then we've created a foreign key called fk_supplier on the products table that references the supplier table based on the supplier_id field.

Because of the cascade delete, when a record in the supplier table is deleted, all records in the products table will also be deleted that have the same supplier_id value.

We could also create a foreign key (with a cascade delete) with more than one field as in the example below:

In this example, our foreign key called fk_foreign_comp references the supplier table based on two fields - the supplier_id and supplier_name fields.

The cascade delete on the foreign key called fk_foreign_comp causes all corresponding records in the products table to be cascade deleted when a record in the supplier table is deleted, based on supplier_id and supplier_name.

Using an ALTER TABLE statement

Syntax

The syntax for creating a foreign key with cascade delete in an ALTER TABLE statement in Oracle/PLSQL is:

Example

Let's look at an example of how to create a foreign key with cascade delete using the ALTER TABLE statement in Oracle/PLSQL.

In this example, we've created a foreign key (with a cascade delete) called fk_supplier that references the supplier table based on the supplier_id field.

We could also create a foreign key (with a cascade delete) with more than one field as in the example below:

FOREIGN KEY - это ключ, используемый для соединения двух таблиц вместе.

FOREIGN KEY - это поле (или набор полей) в одной таблице, которое ссылается на первичный ключ в другой таблице.

Таблица, содержащая внешний ключ, называется дочерней таблицей, а таблица, содержащая ключ кандидат, называется ссылочной или родительской таблицей.

Посмотрите на следующие две таблицы:

PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20

OrderID OrderNumber PersonID
1 77895 3
2 44678 3
3 22456 2
4 24562 1

Обратите внимание, что столбец "PersonID" в таблице "Orders" указывает на столбец "PersonID" в таблице "Persons".

Столбец "PersonID" в таблице "Persons" является первичным ключом в таблице "Persons".

Столбец "PersonID" в таблице "Orders" является внешним ключом в таблице "Orders".

Ограничение внешнего ключа используется для предотвращения действий, которые могут привести к разрушению связей между таблицами.

Ограничение внешнего ключа также предотвращает вставку недопустимых данных в столбец внешнего ключа, поскольку это должно быть одно из значений, содержащихся в таблице, на которую он указывает.

SQL FOREIGN KEY в CREATE TABLE

Следующий SQL создает внешний ключ в столбце "PersonID" при создании таблицы "Orders":

CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

SQL Server / Oracle / MS Access:

CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);

Чтобы разрешить именование ограничения внешнего ключа и определить ограничение внешнего ключа для нескольких столбцов, используйте следующий синтаксис SQL:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

SQL FOREIGN KEY в ALTER TABLE

Чтобы создать ограничение внешнего ключа для столбца "PersonID", когда таблица "Orders" уже создана, используйте следующий SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

Чтобы разрешить именование ограничения внешнего ключа и определить ограничение внешнего ключа для нескольких столбцов, используйте следующий синтаксис SQL:

Читайте также: