T-SQL Query : Getting Child nodes of a parent

前端 未结 1 689
名媛妹妹
名媛妹妹 2020-12-22 04:15

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 a

相关标签:
1条回答
  • 2020-12-22 04:28

    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.

    0 讨论(0)
提交回复
热议问题