id | ParentCategory | Name |
---|---|---|
1 | NULL | Household |
2 | 1 | Furniture |
3 | 1 | Appliances |
4 | 2 | Chair |
5 | 2 | Couch |
6 | 2 | Bed |
7 | 3 | Refridgerator |
8 | 3 | Counter |
10 | 3 | Bathroom |
We want each node to display all it's parents back to its root.
This SQL helps.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: bryanv
-- Create date: 11/28/2018
-- Description: gets the whole list from here down
-- =============================================
CREATE FUNCTION dbo.CategoryFullName
(
@CategoryID int
)
RETURNS nvarchar(200)
AS
BEGIN
-- Declare the return variable here
DECLARE @ans nvarchar(200)
declare @parent int
-- Add the T-SQL statements to compute the return value here
select @ans=name, @parent=ParentCategory from Categories where id=@CategoryID
if @parent is not null
BEGIN
set @ans=dbo.CategoryFullName(@parent)+' - '+@ans
END
-- Return the result of the function
RETURN @ans
END
GO
This will look up the current category text, and prepend all parents recursively until it gets to the root.
You can then use this in a computed column to autogenerate the entire category tree.
Now you can automatically get the full tree with a simple select...
...
Bryan Valencia is a contributing editor and founder of Visual Studio Journey. He owns and operates Software Services, a web design and hosting company in Manteca, California.