0

我有以下与 SQL Server 2012 一起使用的 DDL:

CREATE TABLE Subject (
   [SubjectId] INT IDENTITY (1, 1) NOT NULL,
   [Name] NVARCHAR (50) Not NULL,
   CONSTRAINT [PK_Subject] PRIMARY KEY CLUSTERED ([SubjectId] ASC)
)           

CREATE TABLE Topic (
   [TopicId] INT IDENTITY (1, 1) NOT NULL,
   [Name] NVARCHAR (50) NOT NULL,
   [SubjectId] INT NOT NULL,
   CONSTRAINT [PK_Topic] PRIMARY KEY CLUSTERED ([TopicId] ASC)
)
ALTER TABLE [Topic] WITH CHECK ADD  CONSTRAINT [FK_TopicSubject] 
   FOREIGN KEY([SubjectId]) REFERENCES [Subject] ([SubjectId]) 
   ON DELETE CASCADE

CREATE TABLE SubTopic (
   [SubTopicId] INT IDENTITY (1, 1) NOT NULL,
   [TopicId] INT NOT NULL,
   [Name] NVARCHAR (4000) Not NULL,
   CONSTRAINT [PK_SubTopic] PRIMARY KEY CLUSTERED ([SubTopicId] ASC)
)

ALTER TABLE [SubTopic] WITH CHECK ADD  CONSTRAINT [FK_SubTopicTopic] 
   FOREIGN KEY([TopicId]) REFERENCES [Topic] ([TopicId]) 
   ON DELETE CASCADE

当我尝试运行脚本时,我收到以下消息:

{"Introducing FOREIGN KEY constraint 'FK_TopicSubject' 
on table 'Topic' may cause cycles or multiple cascade paths. 
Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, 
or modify other FOREIGN KEY constraints.\r\nCould not create constraint. 
See previous errors."}

我真正需要的是当一个人在有主题删除失败时尝试删除主题时。如果我既不包括 DELETE ON CASCADE 也不包括 DELETE NO ACTION 那么这会发生。如果没有,那么如果该主题有主题,我该如何停止删除该主题?

4

2 回答 2

1

简短的回答是:如果您不想级联更新和删除,请使用 ON DELETE NO ACTION。同样适用于更新。

这是MSDN 文章的副本(它是 SQL Server 2000,但仍然适用相同的规则)

删除无操作

指定如果尝试删除具有由其他表中现有行中的外键引用的键的行,则会引发错误并回滚 DELETE。

更新无动作

指定如果尝试更新行中的键值,其键被其他表中现有行中的外键引用,则会引发错误并回滚 UPDATE。

于 2013-08-01T10:00:20.690 回答
0

Please refer to this link. It has given a detail explanation of this error, and also has suggested to create a trigger as an alternative. Foreign key constraint may cause cycles or multiple cascade paths?

于 2013-07-31T16:23:23.740 回答