![](/img/trans.png)
[英]Delete Parent and child tables without using cascade delete (SQL Server 2012 or .net 4)
[英]SQL Server cascade does not delete the child of a parent where the parent is also a child of another parent
Microsoft SQL Server 2012和ASP.NET
我需要一些帮助,我正在努力,我在数据库中有3个表:
NumberOne > NumberTwo > NumberThree
第一:
第二:
NumberThree
我有一个从id
(第一个)到numberone_id
(第二个)的外键和一个从id
(第二个)到numbertwo_id
(第三个)的外键。 这些键将Cascade
作为其Delete
规则。 现在,当我以编程方式删除第一个表时,第二个和第三个也被删除。 但是当我以编程方式删除第二个表时,我想保留第一个表,第三个应该被删除但是却没有。
为什么这样,我该如何解决这个问题? 提前致谢。
编辑:
按照要求:
CREATE TABLE [dbo].[REACTIONFILES](
[id] [int] IDENTITY(1,1) NOT NULL,
[reactions_id] [int] NOT NULL,
[reactionsFile] [varbinary](max) NOT NULL,
[reactionsName] [varchar](250) NOT NULL,
CONSTRAINT [PK_REACTIONFILES] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
CREATE TABLE [dbo].[REACTIONS](
[id] [int] IDENTITY(1,1) NOT NULL,
[tickets_id] [int] NOT NULL,
[contents] [varchar](150) NOT NULL,
[users_id] [int] NOT NULL,
[reactionStartdate] [date] NOT NULL,
CONSTRAINT [PK_REACTIONS] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[TICKETS](
[id] [int] IDENTITY(1,1) NOT NULL,
[subject] [varchar](50) NOT NULL,
[categories_id] [int] NOT NULL,
[priorities_id] [int] NOT NULL,
[statuses_id] [int] NOT NULL,
[users_id] [int] NOT NULL,
[usergroups_id] [int] NOT NULL,
[isPublic] [bit] NOT NULL,
[devStartdate] [date] NULL,
[devEnddate] [date] NULL,
[devTime] [varchar](50) NULL,
[commentIntern] [varchar](max) NULL,
[commentExtern] [varchar](max) NULL,
[releaseVersion] [varchar](150) NULL,
[ticketStartdate] [date] NOT NULL,
CONSTRAINT [PK_TICKETS] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
我无法重现这一点。 这是一个脚本(我把它放在答案中的原因,即使它是一个评论)。
你能否创建一个演示问题的脚本?
create table one(id int not null primary key)
go
insert into one(id) values (1),(2),(3)
go
create table two(id int not null primary key, one_id int not null references one(id) on delete cascade)
go
insert into two(id,one_id) values (1,1),(2,2),(3,3)
go
create table three(id int not null primary key, two_id int not null references two(id) on delete cascade)
go
insert into three(id,two_id) values (1,1),(2,2),(3,3)
go
delete from one where id = 3
delete from two where id = 2
select * from two
select * from three
select * from one
结果:
id one_id
----------- -----------
1 1
(1 row(s) affected)
id two_id
----------- -----------
1 1
(1 row(s) affected)
id
-----------
1
2
(2 row(s) affected)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.