递归加入订单

时间:2017-03-13 13:06:12

标签: sql sql-server tsql recursion

我有一个包含页面列表的表,其中一些包含父页面。这些页面的顺序非常随机。我需要创建一个递归连接语句来选择Page_Order排序的所有页面,其中列出父项,然后是其子页面。

表:页面

Page_ID | Page_Name | Page_Parent | Page_Order
1       | User      | 2           | 2
2       | Admin     | NULL        | 2
3       | Pages     | 2           | 1
4       | Home      | NULL        | 1
5       | About     | NULL        | 3
6       | Contact   | 5           | 1

我想按以下顺序选择它们(订购父页面,每个页面后跟其子页面):

Page_ID | Page_Name | Page_Parent | Page_Order
4       | Home      | NULL        | 1
2       | Admin     | NULL        | 2
3       | Pages     | 2           | 1
1       | User      | 2           | 2
5       | About     | NULL        | 3
6       | Contact   | 5           | 1

1 个答案:

答案 0 :(得分:2)

这不是你要求的具体内容,但这是实现你想要的方式。这确实限制了你有限数量的子页面,但它不是递归的。

; WITH cte AS (
  SELECT 1 Page_Id, 'User' Page_Name, 2 Page_Parent, 2 Page_Order union 
  SELECT 2, 'Admin   ', NULL, 2 union 
  SELECT 3, 'Pages   ', 2   , 1 union 
  SELECT 4, 'Home    ', NULL, 1 union 
  SELECT 5, 'About   ', NULL, 3 union 
  SELECT 6, 'Contact ', 5   , 1 
)

SELECT  Page_Id, Page_Name, Page_Parent, Page_order, x = CAST(Page_order  AS DECIMAL(18,2))
FROM    cte
WHERE   Page_Parent IS NULL
UNION
SELECT  child.Page_Id, child.Page_Name, child.Page_Parent, child.Page_order, X = CAST(parent.Page_order  AS DECIMAL(18,2)) + ISNULL(CAST(child.Page_order  AS DECIMAL(18,2))/10000, 0)
FROM    cte parent
        LEFT OUTER JOIN cte child 
                ON child.Page_Parent = parent.Page_Id
WHERE child.Page_Id IS NOT NULL
ORDER BY x