1

我有以下 tFather 和 tChild 表:

IF OBJECT_ID('dbo.tChild', 'U') IS NOT NULL
   DROP TABLE dbo.tChild

IF OBJECT_ID('dbo.tFather', 'U') IS NOT NULL
   DROP TABLE dbo.tFather


CREATE TABLE [dbo].[tFather](
    [ID] [bigint] NOT NULL,
    [fld1] [varchar](50) NULL,
CONSTRAINT [PK_tFather] 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]
GO

CREATE TABLE [dbo].[tChild](
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [tFather_ID] [bigint] NULL,
    [fld1] [nvarchar](50) NULL,
CONSTRAINT [PK_tChild] 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]
GO

ALTER TABLE [dbo].[tChild]  WITH CHECK ADD  CONSTRAINT [FK_tChild_tFather] FOREIGN KEY([tFather_ID])
REFERENCES [dbo].[tFather] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[tChild] CHECK CONSTRAINT [FK_tChild_tFather]
GO


INSERT INTO dbo.tFather (ID, fld1) VALUES ('1', 'a')

INSERT INTO dbo.tChild (tFather_ID, fld1) VALUES ('1', 'X')
INSERT INTO dbo.tChild (tFather_ID, fld1) VALUES ('1', 'Y')
INSERT INTO dbo.tChild (tFather_ID, fld1) VALUES ('1', 'Z')

SELECT * FROM dbo.tFather

ID | fld1
---------
 1 | a

SELECT * FROM dbo.tChild

ID | tFather_ID | fld1
----------------------
 1 |          1 | X
 2 |          1 | Y
 3 |          1 | Z

到目前为止,一切都很好 !现在,当我从 tFather 中删除一行时,由于级联删除/更新,所有行都从 tChild 中正常删除

问题是当我从 tChild 删除行时,一切正常,直到我删除最后一行,然后 tFather 中的行也被删除,这很奇怪。

我在同一个数据库中有许多相关的表,它们的行为正常,(当在 tChild 中删除记录时,在 tFather 中没有删除记录(表名是符号,所以你可以理解关系类型))

让我们测试一下行为:

DELETE FROM dbo.tChild WHERE ID='3'

SELECT * FROM dbo.tFather

ID | fld1
---------
 1 | a

SELECT * FROM dbo.tChild

ID | tFather_ID | fld1
----------------------
 1 |          1 | X
 2 |          1 | Y


DELETE FROM dbo.tChild WHERE ID='2'

SELECT * FROM dbo.tFather

ID | fld1
---------
 1 | a

SELECT * FROM dbo.tChild

ID | tFather_ID | fld1
----------------------
 1 |          1 | X


DELETE FROM dbo.tChild WHERE ID='1'

SELECT * FROM dbo.tFather

ID | fld1
---------
          << - HERE IS THE PROBLEM !!! NO ROWS !!!!!

SELECT * FROM dbo.tChild

ID | tFather_ID | fld1
----------------------

什么可能导致这种行为?

任何建议都会很棒

谢谢你

4

1 回答 1

0

我怀疑问题与 ON UPDATE CASCADE 和 ON DELETE CASCADE 有关。但是,您提供的代码可以正常工作,并且级联可以正常工作,即,如果您删除父亲,则其所有孩子都将被删除。

于 2013-05-15T11:31:15.440 回答