SQL - detecting loops in parent child relations

后端 未结 1 1786
不思量自难忘°
不思量自难忘° 2021-01-13 14:01

I have parent child data in excel which gets loaded into a 3rd party system running MS SQL server. The data represents a directed (hopefully) acyclic graph. 3rd party mean

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 14:21

    You can use a recursive CTE to detect loops:

    with prev as (
        select RowId, 1 AS GenerationsRemoved
        from YourTable
        union all
        select RowId, prev.GenerationsRemoved + 1
        from prev
        inner join YourTable on prev.RowId = ParentRowId
        and prev.GenerationsRemoved < 55
    )
    select * 
    from prev
    where GenerationsRemoved > 50
    

    This does require you to specify a maximum recursion level: in this case the CTE runs to 55, and it selects as erroneous rows with more than 50 children.

    0 讨论(0)
提交回复
热议问题