SQL Server 级联删除 ON DELETE CASCADE

时间:2021-08-11 03:39:08
--创建测试主表
CREATE TABLE [dbo].[Test](

[TestID] int NOT NULL, --主表ID

[TestData] [varchar](10) NOT NULL,--主表内容数据

CONSTRAINT [PK_Test_1] PRIMARY KEY CLUSTERED([TestID] ASC)--设置主键

)

GO

--创建测试子表

CREATE TABLE [dbo].[TestDetail](

[TestDetailID] int NOT NULL,--子表ID

[TestID] int NULL, --主表ID

[TestDetailData] [varchar](10) NULL,--子表内容数据

CONSTRAINT [PK_TestDetail] PRIMARY KEY CLUSTERED([TestDetailID] ASC)--子表主键

)

GO

设置外键约束,设置级联删除

--设置外键约束

ALTER TABLE [dbo].[TestDetail] WITH CHECK

ADD CONSTRAINT [FK_TestDetail_Test] FOREIGN KEY([TestID])

REFERENCES [dbo].[Test]([TestID])

ON DELETE CASCADE --设置级联删除

GO

添加测试数据(为主表添加100条数据,每条主表数据对应10条子表数据)

--添加测试数据(为主表添加100条数据,每条主表数据对应10条子表数据)

DECLARE @val int

DECLARE @val2 int

SELECT @val=1

WHILE @val <= 100

BEGIN

INSERT INTO dbo.[Test] VALUES(@val,'测试' + CAST(@val AS VARCHAR))


SELECT @val2=1

WHILE @val2 <= 10

BEGIN

INSERT INTO dbo.[TestDetail] VALUES ((@val*100000)+@val2,@val,'测试' + CAST(@val AS VARCHAR))

SELECT @val2=@val2+1

END

SELECT @val=@val+1



END

GO

select * from [Test]
select * from [TestDetail]

查询结果如下:

SQL Server 级联删除 ON DELETE CASCADE


下面进行删除操作:

delete from [Test] where TestID=1

得到结果如下: SQL Server 级联删除 ON DELETE CASCADE

子表中TestID是1的也同时被删除了!