数据库_级联更新/级联删除_ON UPDATE CASCADE/ON DELETE CASCADE

时间:2022-12-27 03:38:37

ON UPDATE CASCADE / ON DELETE CASCADE

级联更新与级联删除需要设置在从表上,


on update cascade 级联更新
on delete cascade 级联删除
意思是 当你更新或删除主键表时,那么外键表也会跟随一起更新或删除
CREATE TABLE Countries(CountryId INT PRIMARY KEY) 
INSERT INTO Countries (CountryId) VALUES (1) 
INSERT INTO Countries (CountryId) VALUES (2) 
INSERT INTO Countries (CountryId) VALUES (3) 
GO 
CREATE TABLE Cities( CityId INT PRIMARY KEY  ,CountryId INT REFERENCES Countries ON DELETE CASCADE); 
INSERT INTO Cities VALUES(1,1) 
INSERT INTO Cities VALUES(2,1) 
INSERT INTO Cities VALUES(3,2) 
GO 
CREATE TABLE Buyers(CustomerId INT PRIMARY KEY ,CityId INT REFERENCES Cities ON DELETE CASCADE); 
INSERT INTO Buyers  VALUES(1,1), 
INSERT INTO Buyers  VALUES(2,1) 
INSERT INTO Buyers  VALUES(3,2) 
GO 

命令: 
DELETE FROM Countries WHERE CountryId = 1 
结果: 
Countries: 
CountryId 


Cities: 
CityId CountryId 
3 2 
Buyers: 
CustomerId CityId 

ON UPDATE CASCADE的用法和ON DELETE CASCADE差不多