ALTER PROCEDURE [dbo].[p_ReturnEmployeeOrg]
( @BusinessEntityID int = 21 ) **-- NOT WORKING**
AS
SELECT * FROM HumanResources.Employee
;WITH cte_Emp (EmployeeID,ManagerID,Title,EmployeeName,ManagerName,EmployeeLevel)
AS
-- Anchor member definition
(SELECT e.BusinessEntityID,e.MaritalStatus,e.JobTitle,
CAST(c.LastName + ',' + c.FirstName AS VARCHAR(200)),
CAST ('N/A' AS VARCHAR(200)),
CAST (0 AS INT)
FROM HumanResources.Employee e
INNER JOIN Person.Person c
ON e.BusinessEntityID = c.BusinessEntityID
WHERE e.BusinessEntityID = @BusinessEntityID
UNION ALL
-- Recursive member definition
SELECT e.BusinessEntityID,e.MaritalStatus,e.JobTitle,
CAST(c.LastName + ',' + c.FirstName AS VARCHAR(200)),
CAST ('N/A' AS VARCHAR(200)),
CAST (0 AS INT)
FROM HumanResources.Employee e
INNER JOIN Person.Person c
ON e.BusinessEntityID = c.BusinessEntityID)
ORDER BY EmployeeLevel - **NOT WORKING**
EXEC p_ReturnEmployeeOrg 21)
— exec is NOT WORKING, the results are raw data instead of BusinessEntityID = 21
Did you mean to place the first select statement at the end of the stored procedure? There are three pertinent issues to your stored procedure. Firstly, the CTE’s defined but not used in the stored procedure (this is the reason why your sp is returning everything from the employee table). Secondly your exec statement actually cuts through the middle of the CTE definition (I think this might have been formatting error during your posting). The order by statement in the CTE is probably going to cause an error. It’s best to move it out of the CTE.
I moved the select statement down just after the end of the CTE definition and changed the table name from employee to cte_emp. I alos moved your exec statement out of the CTE defintion.
However there are other non-pertinent issues with this. As mentioned by RichardTheKiwi, why is it that you have e.maritalstatus in the CTE definition, but ManagerID in the CTE header? Is businessentityid in the CTE definition meant to be the employeeid in the CTE header?