Get the parent by passing the child code using Hierarchical Data (SQL Server)

Asked

Viewed 207 times

1

How do I get EmployeeID of the father passing the EmployeeID of the child in the table below using the type variable hierarchyid in SQL Server?

  CREATE TABLE Employee
    (
       Node hierarchyid PRIMARY KEY CLUSTERED,
       EmployeeID int UNIQUE NOT NULL,
       EmpName varchar(20) NOT NULL,
       Title varchar(20) NULL
    ) ;
    GO

1 answer

1


You can use the method Getancestor, it returns the hierarchyid for the inserted position.

In your case, it will return the first position. See the example below:

    SELECT 
         EmployeeID 
    FROM 
         Employee
    WHERE 
        [Node] IN (
                   SELECT
                       [Node].GetAncestor(1).ToString()
                   FROM
                       Employee
                   WHERE 
                       EmployeeID=4
                   )

You can also view through the Sqlfiddle

  • Thank you very much, very simple, and thank you for showing the Sqlfiddle, did not know this tool.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.