I have this sql script to create database in mssql:
CREATE TABLE ENTITY (
ID bigint IDENTITY(1,1) NOT NULL,
NAME nvarchar(255) NOT NULL,
PARENT_ID bigint NULL
)
go
ALTER TABLE ENTITY
ADD CONSTRAINT PK_ENTITY PRIMARY KEY CLUSTERED (ID)
WITH FILLFACTOR = 80
go
ALTER TABLE ENTITY
ADD CONSTRAINT FK_ENTITY FOREIGN KEY (PARENT_ID)
REFERENCES ENTITY (ID) ON DELETE CASCADE ON UPDATE CASCADE
go
By design i'd like to create parent->child relations in single table So, just some pseudocode examples:
id | name | parent_id
1 Mother null
2 Steve 1
3 Jack 1
I'd like to remove Mother with all DELETE Cascade childs if needed But after i install this script i receive:
Introducing FOREIGN KEY constraint 'FK_ENTITY' on table 'ENTITY' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Is any solution how i can implement such single table hierarchy correctly?
AFTER DELETEto delete all children of deleted row - user586399INSTEAD OF DELETEtrigger, notAFTER DELETE. The trigger has to delete all child rows before a parent row can be deleted. - Vladimir Baranov