使用HIERARCHYID时尝试获取祖先的列值

时间:2015-05-14 18:06:19

标签: sql sql-server sql-server-2008 sql-server-2008-r2 sql-server-2012

我正在评估HIERARCHYID数据类型,看它是否符合我对项目的需求。我希望用它来获得给定员工ID的经理。我正在查看AdventureWorks DB(2012版)中的表,特别是Person.Person和HumanResources.Employee表。

我的查询是这样的:

SELECT 
    pp.LastName + ', ' + pp.FirstName AS Name,
    CAST(hre.NationalIdNumber AS BIGINT) AS Id,
    hre.LoginID,
    hre.OrganizationNode.GetAncestor(1) AS ManagerId,
    hre.JobTitle,
    hre.BirthDate,
    hre.MaritalStatus,
    hre.Gender,
    hre.HireDate
FROM 
    Person.Person pp
INNER JOIN 
    HumanResources.Employee hre ON pp.BusinessEntityID = hre.BusinessEntityID

现在我预料到因为GetAncestor()是一个CLR函数,我已经能够做一些像hre.OrganizationNode.GetAncestor(1).NationalIdNumber AS ManagerId但我被告知我不值得非常快

我在这里做错了什么?

稍后编辑

四处游戏让我想到这一点,但这不是最佳的(或者是它?)

SELECT
    pp.LastName + ', ' + pp.FirstName AS Name,
    CAST(hre.NationalIdNumber AS BIGINT) AS Id,
    hre.LoginID,
    NULL AS ManagerId,
    hre.JobTitle,
    hre.BirthDate,
    hre.MaritalStatus,
    hre.Gender,
    hre.HireDate,
    hre.OrganizationLevel
FROM 
    Person.Person pp
INNER JOIN 
    HumanResources.Employee hre ON pp.BusinessEntityID = hre.BusinessEntityID
WHERE 
    OrganizationLevel = 0
UNION
SELECT
    pp.LastName + ', ' + pp.FirstName AS Name,
    CAST(hre.NationalIdNumber AS BIGINT) AS Id,
    hre.LoginID,
    CAST(hre2.NationalIDNumber AS BIGINT) AS ManagerId,
    hre.JobTitle,
    hre.BirthDate,
    hre.MaritalStatus,
    hre.Gender,
    hre.HireDate,
    hre.OrganizationLevel
FROM 
    Person.Person pp
INNER JOIN 
    HumanResources.Employee hre ON pp.BusinessEntityID = hre.BusinessEntityID
INNER JOIN 
    HumanResources.Employee hre2 ON hre.OrganizationNode.GetAncestor(1) = hre2.OrganizationNode
ORDER BY
    hre.OrganizationLevel ASC

1 个答案:

答案 0 :(得分:1)

相关的子查询似乎对我有用:

SELECT 
    pp.LastName + ', ' + pp.FirstName AS Name,
    CAST(hre.NationalIdNumber AS BIGINT) AS Id,
    hre.LoginID,
    (
        SELECT NationalIDNumber
        FROM HumanResources.Employee AS m
        WHERE OrganizationNode = hre.OrganizationNode.GetAncestor(1)
    )AS ManagerId,
    hre.JobTitle,
    hre.BirthDate,
    hre.MaritalStatus,
    hre.Gender,
    hre.HireDate
FROM 
    Person.Person pp
INNER JOIN 
    HumanResources.Employee hre ON pp.BusinessEntityID = hre.BusinessEntityID