We have a self-referenced table like this
CREATE TABLE Categories(
Id int IDENTITY(1,1) NOT NULL,
Title nvarchar(200) NOT NULL,
ParentId int NULL,
CONSTRAINT PK_Structures PRIMARY KEY CLUSTERED
(
Id ASC
)
CREATE NONCLUSTERED INDEX IX_Structures_ParentId ON Categories
(
ParentId ASC
)
And a recursive cte to get all ancestors:
Create View Ancestors
as
with A(Id, ParentId) as
(
select Id, Id from Categories
union all
select e.Id, p.ParentId from Categories e
join A p on e.ParentId = p.Id
)
select * from A
Now we query all ancestors of a given Category like:
select * from Ancestors where Id = 1234
It takes 11 seconds for a table just containing 100000 categories, and the execution plan is. The query returns 5 rows for the given
Id
I know I can greatly improve the performance by using hierarchyid
, also I know that sometimes using while
can be more performant, but in a simple case like this, I expect to see a much better performance.
Also, please note that I already have an index on ParentId
(The picture shows the table structure
which is the actual name of Category
table mentioned in the question.
Is there a tuning to greatly improve this performance?