I've got a Product Category table set up using a SQL Server hierarchy id, I'd like to create an auto-complete dropdown in a CMS that returns searches for matching categories but rather than just displaying the matching category name also displays it's hierarchy/path e.g.
User starts searching for "Cat" and in the auto-complete they see
- Pet Products > Cats
- Pet Products > Cats > Cat Food
- Pet Products > Caterpillars
- Pet Activities > Dogs > Catching Games
Is there are simple way to do this? The examples that I've found focus on selecting the parents of a single specific node which is selected first, but I can't find any examples for selecting multiple nodes and then selecting all the parents for the matching nodes.
I'm happy to massage the results into the format outlined above once I've retrieved them from the DB but it's getting the data that seems to be the tricky part.
I'm using SQL Server 2012 (I don't think that matters much though)
Here's my Schema (nothing extraordinary):
CREATE TABLE [dbo].[Category] (
[CategoryId] INT IDENTITY (1, 1) NOT NULL,
[PrimaryProductId] INT NULL,
[CategoryNode] [sys].[hierarchyid] NOT NULL,
[CategoryString] AS ([CategoryNode].[ToString]()) PERSISTED,
[CategoryLevel] AS ([CategoryNode].[GetLevel]()) PERSISTED,
[Title] NVARCHAR (50) NOT NULL,
[IsActive] BIT DEFAULT ((1)) NOT NULL,
CONSTRAINT [Category_CategoryId_PK] PRIMARY KEY CLUSTERED ([CategoryId] ASC),
CONSTRAINT [Category_Product_PrimaryProductId] FOREIGN KEY (PrimaryProductId) REFERENCES [dbo].[Product](ProductId),
UNIQUE NONCLUSTERED ([CategoryNode] ASC)
);
Here's an example for parents of a single row:
DECLARE @person hierarchyid
SELECT @person = Id
FROM dbo.HierachyTable
WHERE [Name] = 'Joe Blow';
SELECT
Id, Id.ToString() AS [Path],
Id.GetLevel() AS [Level],
Id.GetAncestor(1),
Name
FROM
dbo.HierarchyTable
WHERE
@person.IsDescendantOf(Id) = 1