SQL:奇怪的行为,删除子表上的最后一个相关行删除父表上的行

时间:2013-05-15 10:22:33

标签: sql sql-server sql-server-2012

我有以下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
----------------------

什么可能导致这种行为?

任何建议都会很棒

谢谢

1 个答案:

答案 0 :(得分:0)

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