Deleting a record in a table with foreign key relational tables

Hi guys i'm new to the database

my question is how to delete records in a table that has a foreign key relationship, suppose I have 2 table employees and a department that has deptID as a relation now I want to delete a specific row in the table, such as delete from the department where depID = 10 ", it’s okay if the department’s employees are removed, and I also want to maintain the foreign key relationship. can anyone plz provide me a request for this

thanks

+3
source share
5 answers

, delete employee. , , .

, SQL Server:

CREATE TABLE Employee
(
    DepId INT NOT NULL REFERENCES Department(DepId) ON DELETE CASCADE
)
+2

, . , , " ", NULL FK- . . , NULLIFY CASCADE , .

+1

SQL Server CASCASE DELETE

DELETE Employees, DELETE .

0

, ( , MS SQL Server), . , " , , ". .

0

DB2 ( , ):

Create table Employee
...
... 
FOREIGN KEY (deptID) REFERENCES department (deptID)
    ON DELETE CASCADE

CASCADE, , .

CASCADE RESTRICT, dept, , , .

Alternatively, if you do not want this to happen every time, then it is better to specify RESTRICT and first delete on emp wherever reqd

Delete * from Employee where deptID = 10;
Delete * from Dept where deptID = 10;

Here is a link to examples

0
source

Source: https://habr.com/ru/post/1708317/


All Articles