SQL Server外键约束错误

时间:2015-11-01 11:47:20

标签: sql sql-server visual-studio

我有下表:

CREATE TABLE [dbo].[Comment]
(
    [CommentID] INT NOT NULL PRIMARY KEY, 
    [CommentContent] NVARCHAR(MAX) NULL, 
    [CommentDateTime] DATETIME2 NULL, 
    [ArticleID] INT NULL,
    [ResponseTo] INT NULL, 

    CONSTRAINT [FK_dbo.Comment_dbo.Article_ArticleID] 
        FOREIGN KEY ([ArticleID]) 
        REFERENCES [dbo].[Article] ([ArticleID]) ON DELETE CASCADE,

    CONSTRAINT [FK_dbo.Comment_dbo.Comment_ResponseTo] 
        FOREIGN KEY ([ResponseTo]) 
        REFERENCES [dbo].[Comment] ([CommentID]) ON DELETE CASCADE
)

我得到关于无法创建约束的错误:

  

错误:SQL72014:.Net SqlClient数据提供者:
  消息1785,级别16,状态0,行1   在表'Comment'上引入FOREIGN KEY约束'FK_dbo.Comment_dbo.Comment_ResponseTo'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

它说了一些关于周期...我该如何解决?

1 个答案:

答案 0 :(得分:0)

CASCADE更改为NO ACTION

CREATE TABLE [dbo].[Comment]
(
    [CommentID] INT NOT NULL PRIMARY KEY, 
    [CommentContent] NVARCHAR(MAX) NULL, 
    [CommentDateTime] DATETIME2 NULL, 
    [ArticleID] INT NULL,
    [ResponseTo] INT NULL, 
    CONSTRAINT [FK_dbo.Comment_dbo.Article_ArticleID] FOREIGN KEY ([ArticleID]) 
        REFERENCES [dbo].[Article] ([ArticleID]) ON DELETE CASCADE,
    CONSTRAINT [FK_dbo.Comment_dbo.Comment_ResponseTo] FOREIGN KEY ([ResponseTo]) 
        REFERENCES [dbo].[Comment] ([CommentID]) ON DELETE NO ACTION
)