SQL級聯刪除——刪除主表同時刪除從表——同時刪除具有主外鍵關係的表
create table a
(
id varchar(20) primary key,
password varchar(20) not null
)
create table b
(
id int identity(1,1) primary key,
name varchar(50) not null,
userId varchar(20),
foreign key (userId) references a(id) on delete cascade
)
表B創建了外碼userId 對應A的主碼ID,聲明瞭級聯刪除
測試數據:
insert a values ('11','aaa')
insert a values('23','aaa')
insert b values('da','11')
insert b values('das','11')
insert b values('ww','23')
刪除A表內id爲‘11’的數據,發現B表內userId 爲“11”也被數據庫自動刪除了,這就是級聯刪除
delete a where id='11'
(
id varchar(20) primary key,
password varchar(20) not null
)
create table b
(
id int identity(1,1) primary key,
name varchar(50) not null,
userId varchar(20),
foreign key (userId) references a(id) on delete cascade
)
表B創建了外碼userId 對應A的主碼ID,聲明瞭級聯刪除
測試數據:
insert a values ('11','aaa')
insert a values('23','aaa')
insert b values('da','11')
insert b values('das','11')
insert b values('ww','23')
刪除A表內id爲‘11’的數據,發現B表內userId 爲“11”也被數據庫自動刪除了,這就是級聯刪除
delete a where id='11'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.