How to iterate through an SQL table which “parent” and child" rows are in same table

守給你的承諾、 提交于 2019-12-14 03:47:39

问题


In a table there are the columns ID, Title and ParentID. ParentID is used for the ID of the entry in the same table which is considered its parent - thus any entry in which ParentID is NULL is one which is itself a parent.

I need a query which will iterate through each parent and list any child below it (ideally with a hyphen or something to denote its subordination) does anyone know how this can be done or how to point me in the right direction?

(I've looked into T-SQL and read many similar online questions however my SQL isn't quite sharp enough to make sense of it, so I'd greatly appreciate some pointers!)


回答1:


Here you are!

WITH n(ID, Title) AS 
                    (SELECT ID, Title
                    FROM YourTable
                    WHERE ID = (SELECT TOP 1 ID FROM YourTable WHERE ParentID IS NULL)
                    UNION ALL 
                    SELECT nplus1.ID, nplus1.Title
                    FROM YourTable as nplus1, n 
                    WHERE n.ID = nplus1.ParentID) 
                    SELECT ID, Title FROM n



回答2:


To get hierarchy data from self-referencing table, you can use WITH syntax in sql 2008

  WITH n(ID) AS 
   (SELECT ID FROM YourTable 
   UNION ALL 
   SELECT nplus1.ID
   FROM YourTable as nplus1, n 
   WHERE n.ID = nplus1.ParentID) 
   SELECT ID FROM n


来源:https://stackoverflow.com/questions/11720717/how-to-iterate-through-an-sql-table-which-parent-and-child-rows-are-in-same-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!