Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Server version of Oracle's CONNECT BY in LINQ to show hierachy
    primarykey
    data
    text
    <p>I have successfully simulated an Oracle CONNECT BY statement in SQL Server 2008 by following these 2 previous answers <a href="https://stackoverflow.com/questions/959804/simulation-of-connect-by-prior-of-oracle-in-sql-server">here</a> and <a href="https://stackoverflow.com/questions/2200636/oracle-connect-by-clause-equivalent-in-sql-server">here</a> and adjusting to get the results I need. But how do I do this in LINQ?</p> <p>Here is an example of what I am doing using a dummy database:</p> <pre><code>CREATE TABLE Employee( EmployeeID INT IDENTITY(1,1) PRIMARY KEY, Department INT NOT NULL, EmployeeName VARCHAR(40) NOT NULL, PeckingOrder INT NOT NULL, HigherDepartment INT NULL) INSERT INTO Employee (Department,EmployeeName,PeckingOrder,HigherDepartment) VALUES (1,'Bart',1,NULL),(2,'Homer',1,1),(2,'Marge',2,NULL), (3,'Lisa',1,2),(3,'Maggie',2,2),(3,'Santas Helper',3,1) EmployeeID Department EmployeeName PeckingOrder HigherDepartment 1 1 Bart 1 NULL 2 2 Homer 1 1 3 2 Marge 2 NULL 4 3 Lisa 1 2 5 3 Maggie 2 2 6 3 Santas Helper 3 1 </code></pre> <p>and this is the SQL used to return the heirachy:</p> <pre><code>WITH n(level, PeckingOrder, Department, EmployeeName, HigherDepartment) AS (SELECT 1, PeckingOrder, Department, EmployeeName, HigherDepartment FROM Test.dbo.Employee WHERE Department = 3 UNION ALL SELECT n.level + 1, nplus1.PeckingOrder, nplus1.Department, nplus1.EmployeeName, nplus1.HigherDepartment FROM Test.dbo.Employee as nplus1 JOIN n ON n.HigherDepartment = nplus1.Department) SELECT MAX(level) AS level, PeckingOrder, Department, EmployeeName, HigherDepartment FROM n GROUP BY PeckingOrder, Department, EmployeeName, HigherDepartment ORDER BY MAX(level) DESC, PeckingOrder ASC level PeckingOrder Department EmployeeName HigherDepartment 3 1 1 Bart NULL 2 1 2 Homer 1 2 2 2 Marge NULL 1 1 3 Lisa 2 1 2 3 Maggie 2 1 3 3 Santas Helper 1 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload