简体   繁体   中英

Foreign key linked with primary key in same table

I have a table Categories with columns Id, ParentId (for "subcategories" whom can have any level of nesting) and some other. Using SQL Server 2012 I can't make foreign key in same table, FK_Categories_Categories ( Id -> ParentId ).

Error message is

'Categories' table
- Unable to create relationship 'FK_Categories_Categories'. The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Categories_Categories". The conflict occurred in database "pokupaykadb", table "dbo.Categories", column 'Id'.

That needs for cascade deletion of subcategories. What solution can be? It's desirable to be a some property, like cascade deletion from another table by foreign key

http://i.stack.imgur.com/kXiMS.png

If there are orphaned records that does not meet your constraint criteria - delete them before creating the foreign key.

Usually there are few records which doesn't go by the new constraint and that the DBMS doesn't allow to create the constraint.

In the case of orphaned values, the first occurrence is provided in the error label with the value that is orphaned.

It would certainly have helped to see what code you have tried to execute. Below is a valid table definition :

CREATE TABLE dbo.Categories
(
    Id int NOT NULL IDENTITY(-2147483648, 1)
        CONSTRAINT PK_Categories PRIMARY KEY
    , ParentId int NOT NULL
        CONSTRAINT FK_Categories_ParentId
        FOREIGN KEY (ParentId) REFERENCES dbo.Categories
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM