SQL 级联删除与级联更新的方法

编程学习 2021-07-05 13:42www.dzhlxh.cn编程入门
SQL 级联删除与级联更新的方法,需要的朋友可以参考一下

代码如下:

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)

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)

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)

此外还有级联更新
on update cascade

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板