Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

sql server - T-SQL Query : Getting Child nodes of a parent

I have a table with the following schema :

ID , CatID, ParentCatID, SiteID

I want to get all the sites that belong to the categories that are the roots ( means their ParentCatID = 0) and all their descendants.

for example :

ID , CatID, ParentCatID, SiteID
--------------------------------
1  , 2    , 0          , 3
1  , 4    , 2          , 6
1  , 5    , 4          , 7

In this example CatID 2 is the parent of 4 and 4 is the parent of 5.

How can I get all the SiteIDs that belongs to the root category and all its descendants.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using a recursive Common Table Expression, supported on SQL Server 2005+:

WITH hierarchy AS (
  SELECT yt.id, 
         yt.catid,
         yt.parentcatid,
         yt.siteid
    FROM YOUR_TABLE yt
   WHERE yt.parentcatid = 0
  UNION ALL
  SELECT yt.id, 
         yt.catid,
         yt.parentcatid,
         yt.siteid
    FROM YOUR_TABLE yt
    JOIN hierarchy h ON h.catid = yt.catid)
SELECT t.*
  FROM hierarchy t
OPTION (maxrecursion 1000)

If you get:

The statement terminated. The maximum recursion 100 has been exhausted before statement completion

The default is 100 recursions. The maximum number of recursions can be set via the maxrecursion option, up to a maximum of 32767.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...