實施例的表結構:SQL:優化遞歸CTE
EmployeeId TeamleaderId TopTeamleaderId LEVEL ParentTree CompanyId
1 0 0 0 NULL 1
2 1 1 1 2>1 1
3 2 1 2 3>2>1 1
TeamleaderId
是foreignKey
參照EmployeeId
在同一表
目標: 每當行被插入在表中與EmployeeId
,TeamleaderId
,CompanyId
自動填充TopTeamleaderId
,LEVEL
和ParentTree
與AFTER INSERT
觸發
代碼:
WITH CTE AS (
SELECT EmployeeId, TeamleaderId,0 AS [Level], CAST(EmployeeId AS varchar(100)) AS Heirarchy, TopTeamleaderId
FROM dbo.Employee
WHERE EmployeeId IN (SELECT EmployeeId FROM Employee WHERE TeamleaderId IS NULL
AND CompanyId IN(SELECT DISTINCT CompanyId FROM INSERTED))
UNION ALL
SELECT mgr.EmployeeId, mgr.TeamleaderId, CTE.[Level] +1 AS [Level],
CAST((CAST(mgr.EmployeeId AS VARCHAR(100)) + '>' + CTE.Heirarchy) AS varchar(100)) AS Heirarchy, CTE.TopTeamleaderId
FROM CTE
INNER JOIN dbo.Employee AS mgr
ON TaskCTE.EmployeeId = mgr.ParentTeamleaderId
)
UPDATE Employee SET [LEVEL] = TC.[LEVEL], ParentTree = TC.Heirarchy, TopTeamleaderId = TC.TopTeamleaderId
FROM dbo.Employee AS Employee
JOIN (SELECT * FROM CTE WHERE EmployeeId IN(SELECT DISTINCT EmployeeId FROM INSERTED) AND ParentTeamleaderId IS NOT NULL) TC
ON
Employee.EmployeeId = TC.EmployeeId
問題: 想象有像百萬員工在一個公司,這個查詢需要很長的時間來執行。如何優化它,以便只有插入行的父母纔會被記錄下來?
什麼是你的樓內設有商務規則來做到這一點?請解釋並舉個例子。 –
看到規則不明確,也沒有你的餐桌設計的目的。下腳本是好的,但在你的腳本之上,即使從遞歸CTE的角度來看也是錯誤的。它也可以被優化。 – KumarHarsh