T-SQL递归查询-数据沿袭

时间:2019-01-17 11:51:32

标签: sql tsql recursive-query

给出下表

enter image description here

我需要获取数据库对象的“数据沿袭”。

预期的输出(类似这样):

enter image description here

这是我尝试过的脚本。

CREATE TABLE #smth
     (
         ParObj   NVARCHAR(200)
         ,ChilObj NVARCHAR(200)
     );


INSERT INTO #smth (
    ParObj
    ,ChilObj
)
VALUES ( N'FactSales', N'qryFactSales' )
       ,( 'qryFactSales', 'qryFactSalesOnlineUnited' );

WITH cte
    AS (
           SELECT ParObj
                  ,ChilObj
                  ,level = 1
                  ,path = CAST('root' AS VARCHAR(100))
           FROM   #smth
           UNION ALL
           SELECT t2.ParObj
                  ,t2.ChilObj
                  ,level = t1.level + 1
                  ,Path = CAST(t1.path + ' ||| ' + CAST(t2.ChilObj AS VARCHAR(100)) AS VARCHAR(100))
           FROM   #smth AS t2
                  JOIN cte AS t1
                      ON t1.ChilObj = t2.ParObj
       )
SELECT   *
FROM     cte
ORDER BY cte.path;

它甚至可以通过某种方式实现吗?

1 个答案:

答案 0 :(得分:2)

此版本可满足您的需求:

with cte as (
      select parobj as obj, convert(nvarchar(max), NULL) as path
      from smth
      where not exists (select 1 from smth smth2 where smth2.chilobj = smth.parobj)
      union all
      select smth.chilobj as obj, convert(nvarchar(max), coalesce(path + ' -> ', '')) + cte.obj
      from cte join
           smth
           on cte.obj = smth.parobj
     )
select obj, coalesce(path + ' -> ' + obj, 'Root')
from cte;

Here是db <>小提琴。