0
  1. Trees.DirectReports 是一个闭包(层次结构)表。
  2. 有一个名为Users:的表RowID, EmployeeId, and MangerId@RowCount是该表中的记录数,是该表#EmpMgr的游标。

下面是我想从基于游标的操作转换为基于集合的操作的相关 sql 代码。

WHILE @RowCount <= @NumberRecords --loop through each record in Users table
BEGIN       
    SET @EmpId = (SELECT EmployeeId FROM #EmpMgr WHERE RowID = @RowCount)
    SET @MgrId = (SELECT ManagerId FROM #EmpMgr WHERE RowID = @RowCount)

    INSERT INTO [Trees].[DirectReports](EmployeeId, ManagerId, Depth)
    SELECT c.EmployeeId, p.ManagerId, p.Depth + c.Depth + 1
    FROM Trees.DirectReports p join Trees.DirectReports c
    WHERE p.EmployeeId = @MgrId AND c.ManagerId = @EmpId

    SET @RowCount = @RowCount + 1
END

所以我真的很想弄清楚如何将其作为一个集合查询来执行,因为我知道这样会快得多,但我的大脑今天还没有建立正确的连接来解决这个问题。

*请注意,要回答这个问题,您需要已经了解闭包表的工作原理。否则上面的内容可能没有意义。

4

1 回答 1

2

在其他几篇文章的帮助下找到了我正在寻找的东西。主要答案是这样的:

WITH cte AS
(
    SELECT LegacyId ancestor, LegacyId descendant, 0 depth FROM Users
    UNION ALL

    SELECT cte.ancestor, u.LegacyId descendant, cte.depth + 1 depth
    FROM   dbo.Users u JOIN cte ON u.ManagerId = cte.descendant
)
select * from cte

However, what threw me off at first was that there was some bad data causing circular dependencies. I was able to use the following query to identify where those instances were:

with cte (id,pid,list,is_cycle) 
as
(
    select      legacyid id, managerid pid,',' + cast (legacyid as varchar(max))  + ',',0
    from        users

    union all

    select      u.legacyid id, 
                u.managerid pid, 
                cte.list + cast(u.legacyid as varchar(10)) +  ',' ,case when cte.list like '%,' + cast (u.legacyid as varchar(10)) + ',%' then 1 else 0 end
    from        cte join users u on u.managerid = cte.id
    where       cte.is_cycle = 0
)
select      *
from        cte
where       is_cycle = 1

Once I corrected the cyclical data everything worked great. Check out the following SO posts for more information as these are what I used to come up with my solution: Is there a way to detect a cycle in Hierarchical Queries in SQL Server? and How can I create a closure table using data from an adjacency list?

于 2019-05-26T21:37:18.160 回答