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
所以我真的很想弄清楚如何将其作为一个集合查询,因为我知道这样做会更快,但是我的大脑今天还没有建立适当的联系来解决这个问题。
*请注意,要回答此问题,您将需要已经了解闭包表的工作原理。否则,上面的内容可能没有意义。
答案 0 :(得分: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
但是,起初让我失望的是,有一些不良数据导致循环依赖。我能够使用以下查询来确定这些实例在哪里:
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
一旦我更正了周期性数据,一切都会很好。请查看以下SO帖子以获取更多信息,因为这些是我用来提出解决方案的内容:Is there a way to detect a cycle in Hierarchical Queries in SQL Server?和How can I create a closure table using data from an adjacency list?