Sql-Server
我如何使用自引用員工表檢測一個人向誰報告?
我有一個典型的自引用員工表。數據是分層的,我使用以下 UDF 來封裝一個簡單的 CTE,以導出特定人員的直接和間接報告的輸出。也就是說,我可以傳入單個員工並獲取他們以及他們下的每個人的列表。
我想創建一個類似的功能,允許我獲取老闆和員工參數並檢測員工是否向老闆報告(或老闆參數確實是老闆 - 直接或間接的員工)
使用下面概述的數據庫結構來完成這個邏輯的最佳方法是什麼?
CREATE TABLE [dbo].[Employees]( [EmployeeId] [int] NOT NULL, [managerId] [int] NULL, [FirstName] [nvarchar](50) NOT NULL, [LastName] [nvarchar](50) NOT NULL, [FullName] [nvarchar](100) NOT NULL, [CorpEmailAddress] [nvarchar](510) NULL ) ON [PRIMARY] ALTER FUNCTION [dbo].[fnGetEmployeeHierarchy] ( @EmployeeId int = null ) RETURNS TABLE AS RETURN ( WITH yourcte AS ( SELECT EmployeeId, ManagerID, AMRSNTID, FullName--, Name FROM Employees WHERE EmployeeId = isnull(@EmployeeId,EmployeeId) UNION ALL SELECT e.EmployeeId, e.ManagerID, e.AMRSNTID, e.FullName--, e.Name FROM Employees e JOIN yourcte y ON e.ManagerID = y.EmployeeId ) SELECT EmployeeId, ManagerID, AMRSNTID, FullName--, Name FROM yourcte )
如果您只想在比較員工和經理時返回真或假,請嘗試以下操作:
CREATE FUNCTION [dbo].[fnGetEmployeeHierarchy] ( @EmployeeId INT, @ManagerId INT ) RETURNS BIT AS BEGIN DECLARE @return BIT; SET @return = 0; WITH yourcte AS ( SELECT EmployeeId, ManagerID, FullName FROM Employees WHERE EmployeeId = @EmployeeId UNION ALL SELECT e.EmployeeId, e.ManagerID, e.FullName FROM Employees e INNER JOIN yourcte y ON e.EmployeeId = y.ManagerId ) SELECT @return = 1 FROM yourcte WHERE EmployeeId = @ManagerId; RETURN @return; END