如何正确创建递归查询?

时间:2016-09-01 10:17:27

标签: sql sql-server

我有一张桌子:

ItemID     ParentID             ItemName
  0          NULL                England
  50         0                   Hampshire county
  401        50                  Southampton
  402        50                  Portsmouth

我想要的是下表:

ItemID     Level        ItemName                ItemPath
  0          0           England                 England
  50         1           Hampshire county        England\HampshireCounty
  401        2           Southampton             England\HampshireCounty\Southampton
  402        2           Portsmouth              England\HampshireCounty\Portsmouth

我创建了以下查询:

WITH tree (A_ItemName, A_ItemId, A_Level, pathstr)
AS (SELECT ItemName, ItemId, 0, 
         CAST('' AS VARCHAR(MAX)) 
     FROM Items 
     WHERE ParentID IS NULL 
     UNION ALL 
     SELECT ItemName, ItemID, t.A_Level + 1, t.pathstr + '/' + V.ItemName
     FROM Items V 
         INNER JOIN tree t 
             ON t.A_ItemId = V.ItemID) 
SELECT SPACE(A_Level) + A_ItemName as A_ItemName, A_ItemId, A_Level, pathstr 
FROM tree 
ORDER BY pathstr, A_ItemId

但是,我有一个错误:

  

声明终止。最大递归100已经用尽   在声明完成之前。

知道我做错了吗?

2 个答案:

答案 0 :(得分:5)

你错过了父母。我认为这样做你想要的:

WITH tree (A_ItemName, A_ItemId, A_Level, pathstr) AS (
      SELECT ItemName, ItemId, 0, CAST(ItemName AS VARCHAR(MAX)) 
      FROM Items 
      WHERE ParentID IS NULL 
      UNION ALL 
      SELECT ItemName, ItemID, t.A_Level + 1, t.pathstr + '/' + V.ItemName
      FROM Items V INNER JOIN
           tree t 
           ON t.A_ItemId = V.ParentId
     ) 
SELECT SPACE(A_Level) + A_ItemName as A_ItemName, A_ItemId, A_Level, pathstr 
FROM tree 
ORDER BY pathstr, A_ItemId

答案 1 :(得分:2)

使用以下脚本包含父标记('England')。

WITH tree (A_ItemName, A_ItemId, A_Level, pathstr) AS (
      SELECT ItemName, ItemId, 0, CONVERT(VARCHAR(MAX),ItemName)
      FROM #t  
      WHERE ParentID IS NULL 
      UNION ALL 
      SELECT ItemName, ItemID, t.A_Level + 1, t.pathstr + '/' + V.ItemName
      FROM #t V INNER JOIN
           tree t 
           ON ISNULL(t.A_ItemId,0) = V.ParentId
     ) 
SELECT SPACE(A_Level) + A_ItemName as A_ItemName, A_ItemId, A_Level, pathstr 
FROM tree 
ORDER BY pathstr, A_ItemId