I need to model an n-level tree in SQL Server. I originally did something like this to create a Node
table:
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[ParentId] [bigint] NULL
It's a self referential table, where ParentID
refers back to another Node
entity (the root has a null
ParentID
).
But when I try to add a constraint to cascade deletes, I get this:
Introducing FOREIGN KEY constraint 'FK_dbo.Nodes_dbo.Nodes_ParentId' on table 'Nodes' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
From what I read, this seems to be a pretty well known, and reasonable limitation in SQL Server. Some people suggest using a trigger to accomplish this, but I'd prefer to avoid that if possible.
So my question is - how should an n-level hierarchy or tree be modelled in SQL in order to allow cascading deletes?
I'm using SQL Server 2012.