2017-05-25 41 views
0

我有三個表:(經典)循環或多個級聯路徑異常

CREATE TABLE Items (
    [ItemId] int   not null identity(1,1) 
    ,[ItemName] nvarchar(250) not null 
    -- other colums related to item 
) 

CREATE TABLE Categories (
    [CategoryId] int   not null identity(1,1) 
    ,[CategoryName] nvarchar(50) not null 
    -- other colums related to category 
) 

CREATE TABLE ItemCategories (
    [ItemId]  int not null 
    ,[CategoryId] int not null 

    ,CONSTRAINT [PK_ItemCategories] PRIMARY KEY CLUSTERED ([ItemId], [CategoryId]) 
    ,CONSTRAINT [FK_ItemCategories_Items] FOREIGN KEY ([ItemId]) 
    REFERENCES Items ([ItemId]) 
    ON DELETE CASCADE --ON UPDATE CASCADE 
    ,CONSTRAINT [FK_ItemCategories_Categories] FOREIGN KEY ([CategoryId]) 
    REFERENCES Categories ([CategoryId]) 
    ON DELETE CASCADE --ON UPDATE CASCADE 
) 

經典的問題,但它有我的疑惑。

[ItemCategories]表是存儲[ItemId]和[CategoryId]之間關係的唯一表。

當[記錄]從[Items]或[Categories]中被刪除時,我想要的所有記錄都將從[ItemCategories]中刪除。

其他人可以盯着代碼看看我是不是正確地聲明瞭一些東西?乾杯。

回答

1

該代碼看起來不錯。

CREATE TABLE Items (
    [ItemId] int not null identity(1,1) primary key 
    ,[ItemName] nvarchar(250) not null 
    -- other colums related to item 
) 

CREATE TABLE Categories (
    [CategoryId] int not null identity(1,1) primary key 
    ,[CategoryName] nvarchar(50) not null 
    -- other colums related to category 
) 

CREATE TABLE ItemCategories (
    [ItemId]  int not null 
    ,[CategoryId] int not null 

    ,CONSTRAINT [PK_ItemCategories] PRIMARY KEY CLUSTERED ([ItemId], [CategoryId]) 
    ,CONSTRAINT [FK_ItemCategories_Items] FOREIGN KEY ([ItemId]) 
    REFERENCES Items ([ItemId]) 
    ON DELETE CASCADE --ON UPDATE CASCADE 
    ,CONSTRAINT [FK_ItemCategories_Categories] FOREIGN KEY ([CategoryId]) 
    REFERENCES Categories ([CategoryId]) 
    ON DELETE CASCADE --ON UPDATE CASCADE 
) 

go 

insert into items(ItemName) values ('itema') 
insert into Categories(CategoryName) values ('categorya') 
insert into ItemCategories(ItemId,CategoryId) values (1,1) 
go 
delete from items 
go 
select * from ItemCategories --empty 
+0

那你看看我的代碼。這是兩個人(包括我自己)現在確認它看起來不錯。但由於某種原因,當我嘗試執行它時,我得到這些週期或多個級聯路徑異常。我會繼續尋找。 – iiminov

相關問題