all groups > sql server programming > april 2007 >
You're in the

sql server programming

group:

Cascade delete error


Cascade delete error Flomo Togba Kwele
4/28/2007 7:59:43 PM
sql server programming: I'm new at this and need some help. I tried to setup a situation where I delete
the children related to a parent when a parent is deleted. But I am getting an
error. I have changed the names of the columns and tables to make it easier.

Can anyone tell me what I have done wrong? Thanks, Flomo

Parent table
ParentID int PK
...

Child table
ParentID int FK
ZipCode char(5)
...
(Above 2 columns constitute the PK of Child table)

ALTER TABLE [dbo].[Child] WITH CHECK ADD CONSTRAINT [FK_Child_Parent] FOREIGN
KEY([ParentID])
REFERENCES [dbo].[Parent] ([ParentID])
GO
ALTER TABLE [dbo].[Child] CHECK CONSTRAINT [FK_Child_Parent]
GO

Data:
Parent table ParentID=6 (1 row)
Child table ParentID=6 (1 row)

Query:
DELETE FROM Parent WHERE ParentID=6

The DELETE statement conflicted with the REFERENCE constraint
"FK_Child_Parent". The conflict occurred in database "XYZ", table "dbo.Child",
column 'ParentID'.
The statement has been terminated.

--
Re: Cascade delete error Alain Quesnel
4/28/2007 9:51:17 PM
I don't see why you need to add the second statement:
ALTER TABLE [dbo].[Child] CHECK CONSTRAINT [FK_Child_Parent]
GO

What happens if you create your child table with only the first statement
(the one that creates the foreign key)?

Also, you should have a single field primary key on your child table (i.e.
an auto inc integer field). If you want to enforce a unique combination of
ParentID and ZipCode, then define a secondary unique index on those two
fields.

--

Alain Quesnel
alainsanspam@logiquel.com

www.logiquel.com



[quoted text, click to view]

Re: Cascade delete error Tom Cooper
4/28/2007 10:03:52 PM
Foreign key constraints by default do not cascade deletes or updates. The
default is "No Action" which means the update or delete will be rejected if
it will violate the foreign key constraint. If you want to cascade deletes
and/or updates, you must specify that. For example, to cascade deletes, but
not updates, you could use

ALTER TABLE [dbo].[Child] WITH CHECK ADD CONSTRAINT [FK_Child_Parent]
FOREIGN
KEY([ParentID])
REFERENCES [dbo].[Parent] ([ParentID])
ON DELETE CASCADE

To cascade both deletes and updates, you could use

ALTER TABLE [dbo].[Child] WITH CHECK ADD CONSTRAINT [FK_Child_Parent]
FOREIGN
KEY([ParentID])
REFERENCES [dbo].[Parent] ([ParentID])
ON UPDATE CASCADE
ON DELETE CASCADE

Tom

[quoted text, click to view]

Re: Cascade delete error Uri Dimant
4/29/2007 12:00:00 AM
Hi

Be aware that with the large data to be deleted ON DELETE CASCADE may cause
blocking. Also. make sure that FK column has an index



[quoted text, click to view]

AddThis Social Bookmark Button