Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Table relationship. What am I doing wrong?

Author  Topic 

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2008-02-27 : 18:42:42
Hello,

I have 3 tables: Articles, ArticlesTags and Tags.
ArticleTags relate Articles and Tags records.

When I try to delete a record in Tags I get the following error:

The DELETE statement conflicted with the REFERENCE constraint

"FK_ArticlesTags_Tags". The conflict occurred in database "MyDB", table "dbo.ArticlesTags", column 'TagID'.
The statement has been terminated.

What am I doing wrong?

Here is how I am creating my tables:

create table dbo.Articles
(
ArticleID uniqueidentifier not null
constraint PK_Article primary key clustered,
Body nvarchar(max) not null

)
create table dbo.ArticlesTags
(
ArticleID uniqueidentifier not null,
TagID uniqueidentifier not null,
constraint PK_ArticlesTags
primary key clustered (ArticleID, TagID),
constraint FK_ArticlesTags_Articles
foreign key(ArticleID)
references dbo.Articles(ArticleID)
on delete cascade,
constraint FK_ArticlesTags_Tags
foreign key(TagID)
references dbo.Tags(TagID)
)
create table dbo.Tags
(
TagID uniqueidentifier not null
constraint PK_Tag primary key clustered,
[Name] nvarchar(200) not null
)

Basically, what I need is:

1. If an Article is deleted then:
> Delete all records for that Article in ArticlesTags
> Don't delete any Tag in Tags.

2. If an Tag is deleted then:
> Delete all records associated with it in ArticlesTags.
> Don't delete any Article in Articles.

What am I missing?

Thanks,
Miguel

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2008-02-27 : 19:17:37
I found it!

Sorry, I was checking everything and I didn't realized that the following was missing:

constraint FK_ArticlesTags_Tags
foreign key(TagID)
references dbo.Tags(TagID)
on delete cascade <<<<<<<<

Thank You,
Miguel
Go to Top of Page

mahesh_bote
Constraint Violating Yak Guru

298 Posts

Posted - 2008-02-27 : 23:32:29
For the ArticlesTags Articles and Tags are parent tables. So before deleting records from parent tables, delete the concern records from child table.

Thanks,

Mahesh
Go to Top of Page
   

- Advertisement -