2

亲爱的 Stackoverflow 会员

我有一个这样的递归 CTE 查询:

DECLARE @Level TABLE (ID int, ParentID int, Name varchar(max))

INSERT INTO @Level (ID, ParentID, Name)
         VALUES (1,0, 'AAAA'),
                (2,1, 'BBBB'),
                (3,2, 'CCCC'),
                (4,3, 'DDDD'),
                (5,4, 'EEEE')

;WITH cte (ID, ParentID, Name, Path, Level) AS
(
     SELECT 
         ID, ParentID, Name, CONVERT(varchar(MAX), Name), 1
     FROM 
         @Level
     WHERE 
         ParentID = 0

     UNION ALL

     SELECT 
         n.ID, n.ParentID, n.Name, 
         CONVERT(varchar(MAX), cte.Path + '/' + n.Name), cte.Level + 1
     FROM 
         @Level n
     JOIN 
         cte on n.ParentID = cte.ID
   )
   SELECT * FROM cte  

上述查询的结果:

ID          ParentID    Name    Path                         Level
----------- ----------- ------- ---------------------------- -----------
1           0           AAAA    AAAA                         1
2           1           BBBB    AAAA/BBBB                    2
3           2           CCCC    AAAA/BBBB/CCCC               3
4           3           DDDD    AAAA/BBBB/CCCC/DDDD          4
5           4           EEEE    AAAA/BBBB/CCCC/DDDD/EEEE     5

CTE 查询所需的输出:

ID          ParentID    Name   Paths                        Path                         Level
----------- ----------- ----------------------------------- ---------------------------- -----------
1           0           AAAA   AAAA                         AAAA                         1
2           1           BBBB   AAAA/BBBB                    AAAA/BBBB                    2
3           2           CCCC   AAAA/.../CCCC                AAAA/BBBB/CCCC               3
4           3           DDDD   AAAA/.../.../DDDD            AAAA/BBBB/CCCC/DDDD          4
5           4           EEEE   AAAA/.../.../.../EEEE        AAAA/BBBB/CCCC/DDDD/EEEE     5

从上面的示例中可以看出,路径可能会变得很长,并且宁愿将路径替换为点。除了开始和结束字符保持可见并且仅替换中间内容之外。请注意,VALUES 的内容可以是任何内容,这只是作为示例。

谢谢

4

1 回答 1

3

这会折叠除 Root 和 Current 之外的所有内容

   DECLARE @Level TABLE (ID int, ParentID int, Name varchar(max))

        INSERT INTO @Level (ID, ParentID, Name)
         VALUES (1,0, 'AAAA'),
                (2,1, 'BBBB'),
                (3,2, 'CCCC'),
                (4,3, 'DDDD'),
                (5,4, 'EEEE')


        ;WITH cte (ID, ParentID, Name, Root, Path, Level) AS
   (
   SELECT ID, ParentID, Name, CONVERT(varchar(MAX), Name),
          CONVERT(varchar(MAX), Name), 1
   FROM @Level
   WHERE ParentID = 0
   UNION ALL
   SELECT n.ID, n.ParentID, n.Name, cte.Root, cte.Root + '/' +
          CASE WHEN cte.Level=1 then ''
               else replicate('.../', cte.level-1) end +
          n.Name, cte.Level + 1
   FROM @Level n
   JOIN cte on n.ParentID = cte.ID
   )
   SELECT * FROM cte  
于 2012-11-15T14:29:31.373 回答