all groups > sql server (alternate) > august 2006 >
You're in the

sql server (alternate)

group:

Self-Reference cascading deletes


Self-Reference cascading deletes cesar.guinovart NO[at]SPAM gmail.com
8/31/2006 8:44:10 AM
sql server (alternate):
I have the following table

CREATE TABLE [tbl_Items]
(
[item_id] int IDENTITY(1,1) CONSTRAINT PK_tbl_Items__item_id
PRIMARY KEY,
[parent_id] int DEFAULT(NULL) CONSTRAINT
FK_tbl_Items__item_id__parent_id REFERENCES [tbl_Items]( [item_id] ) ON
DELETE NO ACTION ON UPDATE NO ACTION
)


My Intention was to create a table that when I delete a record, all
records that have on the [parent_id] field the deleted record
[item_id].

I am trying to avoid having to use triggers or create a stored
procedure that firsts delete the children (recursively) and then
deletes the parent.

Is there any way to do this by changing my table definition here?
Re: Self-Reference cascading deletes Erland Sommarskog
8/31/2006 9:17:26 PM
(cesar.guinovart@gmail.com) writes:
[quoted text, click to view]

While you can set up cascading foreign keys in some cases, this is not
one of them.

To use a an after trigger, you would have to remove the constraint.

But you could have an INSTEAD OF trigger. If you are using SQL 2000
you would have to first gather all children in a temp table, and
then delete all childre you found. In SQL 2005 you would use a
recursive CTE instead.

As you did not include which version of SQL Server you are using,
and the solutions are completely different, I don't include an example.


--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
AddThis Social Bookmark Button