一对多反身关联INSERT数据

时间:2010-08-11 07:57:10

标签: sql sql-server database

我有一张带有一对多反身关联的表格。

我需要插入第一个禁用临时约束的值。 知道怎么做吗?

我使用MS SQL 2008,谢谢你的支持!

  CREATE TABLE dbo.CmsCategories
    (
        CategoryId      int             NOT NULL    IDENTITY (0,1) -- Seed = 0 and Increment= 1
            CONSTRAINT PK_CmsCategories_CategoryId PRIMARY KEY,
        ParentOf        int             NOT NULL
            CONSTRAINT DF_CmsCategories_ParentOf DEFAULT 0  
    );
ALTER TABLE dbo.CmsCategories
ADD CONSTRAINT FK_CmsCategories_ParentOf FOREIGN KEY (ParentOf) REFERENCES dbo.CmsCategories(CategoryId); -- One-to-many Reflexive association
GO

    INSERT INTO dbo.CmsCategories
    (ParentOf)
    VALUES
    (0);

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,告诉我你的想法谢谢!

-- CmsCategories: Disable constraint one-to-many reflexive association to add first row
    ALTER TABLE dbo.CmsCategories
    NOCHECK
    CONSTRAINT
    FK_CmsCategories_ParentOf;

    ---- CmsCategories: Insert first row - Root value
    INSERT INTO dbo.CmsCategories
    (Title, MetaDescription, MetaKeyword, Summary, IsPublished, ParentOf)
    VALUES
    ('Homepage','Homepage','Homepage','Homepage',1,0);

    -- CmsCategories: Enable constraint one-to-many reflexive association
    ALTER TABLE dbo.CmsCategories
    CHECK
    CONSTRAINT
    FK_CmsCategories_ParentOf;