-3
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不工作,结果是原始数据而不是 BusinessEntityID = 21

4

1 回答 1

1

你的意思是把第一个选择语句放在存储过程的末尾吗?您的存储过程存在三个相关问题。首先,CTE 已定义但未在存储过程中使用(这就是您的 sp 从员工表中返回所有内容的原因)。其次,您的 exec 语句实际上贯穿了 CTE 定义的中间(我认为这可能是您发布期间的格式错误)。CTE 中的 order by 语句可能会导致错误。最好将其移出 CTE。

ALTER PROCEDURE [dbo].[p_ReturnEmployeeOrg]
( @BusinessEntityID int = 21 ) 
AS

;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)
) 
SELECT * FROM cte_emp ORDER BY EmployeeLevel 
--....................  

EXEC p_ReturnEmployeeOrg 21

我在 CTE 定义结束后将 select 语句向下移动,并将表名从雇员更改为 cte_emp。我也将您的 exec 语句移出 CTE 定义。

但是,还有其他与此无关的问题。正如 RichardTheKiwi 所提到的,为什么 CTE 定义中有 e.maritalstatus,而 CTE 标头中有 ManagerID?CTE 定义中的 businessentityid 是否意味着 CTE 标头中的employeeid?

于 2012-10-14T22:46:40.333 回答