假設你們公司層級只有四層,所以這樣寫就可以抓出全公司層級:
<pre class="c" name="code">select E1.EmpName,E2.EmpName,E3.EmpName,E4.EmpName
from EMP as E1
left join EMP as E2 on E1.EmpID=E2.EmpBoss
left join EMP as E3 on E2.EmpID=E3.EmpBoss
left join EMP as E4 on E3.EmpID=E4.EmpBoss
where E1.EmpBoss ='';
如果只要查 Bill,那只需寫:
<pre class="c" name="code">select E2.EmpName,E3.EmpName,E4.EmpName
from EMP as E2
left join EMP as E3 on E2.EmpID=E3.EmpBoss
left join EMP as E4 on E3.EmpID=E4.EmpBoss
where E2.EmpName ='Bill';
如果是SQL Server 2008....可以考慮使用cte...
Common Table Expressions
select * from EMP
先用ADO.NET整個讀到 DataTable Dt
在ASP.NET裡用
string filterExpr = string.Format("EmpBoss = '{0}'", strEmpBoss);
DataRow [] rows = Dt.Select(filterExpr);
自己去處理遞回
一次抓一層
這樣要幾層都OK
但是一樣要檢查資料錯誤導致的無限遞回問題
--cte recursive
;WITH Emp_CTE AS (
SELECT EmpID, EmpName,EmpBoss
FROM Employee
WHERE EmpName='Bill'
UNION ALL
SELECT e.EmpID, e.EmpName, e.EmpBoss
FROM Employee e
INNER JOIN Emp_CTE ecte ON ecte.EmpID = e.EmpBoss
)
SELECT *
FROM Emp_CTE;