Advertisement
RodrigoPvz

Untitled

Nov 17th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.62 KB | None | 0 0
  1. CREATE FUNCTION dbo.ufn_FindReports (@InEmpID INTEGER)  
  2. RETURNS @retFindReports TABLE  
  3. (  
  4.     EmployeeID int primary key NOT NULL,  
  5.     FirstName nvarchar(255) NOT NULL,  
  6.     LastName nvarchar(255) NOT NULL,  
  7.     JobTitle nvarchar(50) NOT NULL,  
  8.     RecursionLevel int NOT NULL  
  9. )  
  10. --Returns a result set that lists all the employees who report to the  
  11. --specific employee directly or indirectly.*/  
  12. AS  
  13. BEGIN  
  14. WITH EMP_cte(EmployeeID, OrganizationNode, FirstName, LastName, JobTitle, RecursionLevel) -- CTE name and columns  
  15.     AS (  
  16.         -- Get the initial list of Employees for Manager n
  17.         SELECT e.BusinessEntityID, e.OrganizationNode, p.FirstName, p.LastName, e.JobTitle, 0  
  18.         FROM HumanResources.Employee e  
  19. INNER JOIN Person.Person p  
  20. ON p.BusinessEntityID = e.BusinessEntityID  
  21.         WHERE e.BusinessEntityID = @InEmpID  
  22.         UNION ALL  
  23.         -- Join recursive member to anchor
  24.         SELECT e.BusinessEntityID, e.OrganizationNode, p.FirstName, p.LastName, e.JobTitle, RecursionLevel + 1  
  25.         FROM HumanResources.Employee e  
  26.             INNER JOIN EMP_cte  
  27.             ON e.OrganizationNode.GetAncestor(1) = EMP_cte.OrganizationNode  
  28. INNER JOIN Person.Person p  
  29. ON p.BusinessEntityID = e.BusinessEntityID  
  30.         )  
  31. -- copy the required columns to the result of the function  
  32.    INSERT @retFindReports  
  33.    SELECT EmployeeID, FirstName, LastName, JobTitle, RecursionLevel  
  34.    FROM EMP_cte  
  35.    RETURN  
  36. END;  
  37. GO  
  38. -- Example invocation  
  39. SELECT EmployeeID, FirstName, LastName, JobTitle, RecursionLevel  
  40. FROM dbo.ufn_FindReports(1);  
  41.  
  42. GO
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement