34,593
社区成员
发帖
与我相关
我的任务
分享
--->>>>TravyLee生成测试数据
if object_id('test')is not null
drop table test
go
create table test(
id int primary key,
value varchar(10)
)
go
insert test(id,value)
select 1,'test1' union all
select 2,'test2' union all
select 3,'test3' union all
select 4,'test4' union all
select 5,'test5'
go
if object_id('tbl')is not null
drop table tbl
go
create table tbl(
id int foreign key references test(id)
on delete cascade --指定级联删除
on update cascade, --指定级联更新
value varchar(5)
)
go
insert tbl
select 1,'true' union all
select 2,'false' union all
select 3,'false' union all
select 4,'true' union all
select 5,'false'
go
delete from test where value='test2'
select * from test
/*
test数据
-------------------------
id value
1 test1
3 test3
4 test4
5 test5
-------------------------
tbl数据
--------------------------
id value
1 true
3 false
4 true
5 false
*/
--级联删除
create table ta(id int not null primary key)
insert ta
select 1
create table tb(id int foreign key references ta(id) on delete cascade)
insert tb
select 1
select * from ta
select * from tb
delete ta
select * from ta
select * from tb
drop table tb
drop table ta
if exists (select 1 from sysobjects where name='FK_Aid_B')
alter table B drop constraint [FK_Aid_B]
go
if object_id('A') is not null drop table A
if object_id('B') is not null drop table B
create table A(
id int not null primary key
)
go
create table B(
id int not null,
AId int not null
)
go
alter table B add constraint [PK_B] primary key clustered(id,AId) on [PRIMARY]
go
alter table B add constraint [FK_Aid_B] foreign key(AId) references A(id)
on delete cascade
go
insert into A select 1 union all select 2
insert into B select 1,1 union all select 2,2
--删除前
select * from A
select * from B
delete A where id=1
--删除后
select * from A
select * from B
go