2014-09-24 53 views
-2

我有這個自引用表,我應該在沒有提供父ID的情況下獲取上線和下線以及層級。T-SQL:確定沒有父ID的層次結構中的上線和下線

任何想法?

+2

如果你想得到任何有用的答案,你的問題就非常模糊了,需要更多的細節。至少應該提供表格模式和一些樣品數據,以及您的預期結果應該基於樣品數據。 – 2014-09-24 13:25:08

回答

0

您是否嘗試過使用遞歸CTE? 例如: 假設你有表TBL(EMPID,名稱,MngrId),它具有自引用關係

create table tbl 
(
EmpId int not null, 
Name nvarchar(100), 
MngrId int null) 

insert into tbl(EmpId, Name, MngrId) 
values (1,'Adel',Null), 
     (2,'Ali',1), 
     (3,'Shaban',1), 
     (4,'Mark',3), 
     (5,'John',3), 
     (6,'Tony',Null), 
     (7,'Peter',6) 

您可以創建這樣一些觀點:

create view Employees 
Begin 

with cte 
as 
(
Select EmpId,Name, Null as MngrId, cast(null as nvarchar(100)) as MngrName, 1 as EmpLevel 
from tbl 
where MngrId is Null 
Union All 
Select t.EmpId, t.Name, c.EmpId as MngrId, c.Name as MngrName, c.EmpLevel + 1 as EmpLevel 
from tbl t 
inner join cte c 
on t.MngrId = c.EmpId 
) 
Select * 
from cte 
order by EmpLevel, EmpId 

End 

您現在可以使用EmpLevel跳轉到不同的級別MngrName得到關於父節點的信息