CTE变量,Exec过程和EmployeeLevel的顺序

时间:2012-10-14 22:28:29

标签: sql sql-server tsql

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

1 个答案:

答案 0 :(得分:1)

您的意思是将第一个select语句放在存储过程的末尾吗?存储过程存在三个相关问题。首先,CTE已定义但未在存储过程中使用(这就是您的sp从employee表返回所有内容的原因)。其次你的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语句向下移动,并将表名从employee更改为cte_emp。我将你的执行声明从CTE定义中删除了。

然而,还有其他非相关问题。正如RichardTheKiwi所提到的,为什么你在CTE定义中有e.maritalstatus,但在CTE标题中有ManagerID? CTE定义中的businessentityid是CTE标题中的employeeid吗?