Saving a site hierarchy in Sql Server 2008

I want to keep the hierarchy of site pages in a table.

What I would like to achieve is effectively 1) allow the (last valid) element along the path (for example, "/blogs/programming/tags/asp.net,sql-server", "/ blogs / programming / hello-world")
2) get ancestral items for baking
3) edit the item without updating the entire tree of children, grandchildren, etc.

Due to the third point, I thought the table might look like

ITEM
id    type        slug           title               parentId
1     area        blogs          Blogs
2     blog        programming    Programming blog    1
3     tagsearch   tags                               2
4     post        hello-world    Hello World!        2

Is there any way to use the hierarchical type of Sql Server (especially paragraph 1, "/ blogs / programming / tags" is the last valid element)?
The depth of the tree is usually about 3-4.

What would be the best way to achieve all this?

+3
1

, , , CTE

-

DECLARE @ITEM  TABLE(
        id INT,
        type VARCHAR(20),
        slug VARCHAR(50),
        title VARCHAR(50),
        parentId  INT
)

INSERT INTO @ITEM SELECT 1,'area','blogs','Blogs', NULL
INSERT INTO @ITEM SELECT 2,'blog','programming','Programming blog',1 
INSERT INTO @ITEM SELECT 3,'tagsearch','tags',',',2 
INSERT INTO @ITEM SELECT 4,'post','hello-world','Hello World!',2 

;WITH Items AS (
        SELECT  *,
                CAST('/' + slug + '/' AS VARCHAR(50)) PathVal
        FROM    @ITEM
        WHERE   parentId IS NULL
        UNION ALL
        SELECT  i.*,
                CAST(Items.PathVal + i.slug + '/' AS VARCHAR(50))
        FROM    Items INNER JOIN
                @ITEM i ON i.parentId = Items.ID
)

SELECT  *
FROM    Items
+1

Source: https://habr.com/ru/post/1739583/


All Articles