fullpath_mssql2008 of SQL SERVER 2008 CTE Generation node

Source: Internet
Author: User
OK, now let's see how to generate FullPath:
Copy Code code as follows:

DECLARE @tbl TABLE
(
Id int
, ParentID int
)
INSERT into @tbl
(Id, ParentID)
VALUES (0, NULL)
, (8, 0)
, (12, 8)
, (16, 12)
, (17, 16)
, (18, 17)
, (19, 17)

with ABCD
As (
--Anchor
SELECT ID
, ParentID
, CAST (id as VARCHAR) as [Path]
From @tbl
WHERE ParentID is NULL
UNION All
--recursive Member
SELECT t.id
, T.parentid
, cast (A.[path] + ', ' + cast (t.id as VARCHAR) as VARCHAR) as [Path]
From @tbl as T
JOIN ABCD as a on t.parentid = a.ID
)
SELECT Id, ParentID, [Path]
from ABCD
WHERE Id not in (SELECT ParentID
From @tbl
WHERE ParentID is not NULL)

Return:
Id ParentID Path
----------- ----------- ----------------------
18 17 0,8,12,16,17,18
19 17 0,8,12,16,17,19
As simple as this, there is actually a hierarchytype in SQL Server 2008 that can solve this problem well. I'll write some post about Hierarchytype in the back.

I hope this post is helpful to you.

Author Peter Liu
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.