Friday, March 23, 2012

ON DELETE CASCADE problem for same table column constraint

Hello,
I would like to have table with foreign key referencing to the column of the
same table. And I want to specify ON DELETE CASCADE to this column, e.g.:
create table category (
ID INTEGER IDENTITY(1,1) NOT NULL,
PARENT_ID INTEGER NULL,
NAME VARCHAR(100) NOT NULL,
CONSTRAINT CAT_PK PRIMARY KEY (ID),
CONSTRAINT CAT_FK FOREIGN KEY (PARENT_ID)
REFERENCES CAT(ID) ON DELETE CASCADE
)
But I receive error:
--
Error: java.sql.SQLException: Introducing FOREIGN KEY constraint 'CAT_FK'
on table 'category' may cause cycles or multiple cascade paths.
Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints., SQL State: S1000, Error Code: 1785

It means I cannot specify ON DELETE CASCADE clause.
HOW CAN I ENSURE CASCADE DELETING FOR ALL RECORDS (ALL CATEGORIES WITH BELONGED SUBCATEGORIES)?
IS THERE POSSIBILITY TO USE STORED PROCEDURE FOR THIS?
CAN YOU POST AN EXAMPLE PLEASE?

Thank you in advance
best regards,
Julian LegenyThis is a restriction in all versions of SQL Server that supports cascading constraints. You will have to implement the cascade action using triggers or in your SPs that perform the data modifications.

No comments:

Post a Comment