GetAncestor (Database Engine)
傳回 hierarchyid,代表 this 的第 n 個上階。
語法
-- Transact-SQL syntax
child.GetAncestor ( n )
-- CLR syntax
SqlHierarchyId GetAncestor ( int n )
引數
- n
int,代表要在階層中向上移動的層級數目。
傳回類型
**SQL Server 傳回類型:**hierarchyid
**CLR 傳回類型:**SqlHierarchyId
範例
A. 尋找父系的子節點
GetAncestor(1) 會傳回具有 david0 當做其直接上階 (其父系) 的員工。下列範例會使用 GetAncestor(1)。
DECLARE @CurrentEmployee hierarchyid
SELECT @CurrentEmployee = OrgNode FROM HumanResources.EmployeeDemo
WHERE LoginID = 'adventure-works\david0'
SELECT OrgNode.ToString() AS Text_OrgNode, *
FROM HumanResources.EmployeeDemo
WHERE OrgNode.GetAncestor(1) = @CurrentEmployee ;
B. 傳回父系的孫系
GetAncestor(2) 會傳回在階層中位於目前節點下面兩個層級的員工。這些就是目前節點的孫系。下列範例會使用 GetAncestor(2)。
DECLARE @CurrentEmployee hierarchyid
SELECT @CurrentEmployee = OrgNode FROM HumanResources.EmployeeDemo
WHERE LoginID = 'adventure-works\ken0'
SELECT OrgNode.ToString() AS Text_OrgNode, *
FROM HumanResources.EmployeeDemo
WHERE OrgNode.GetAncestor(2) = @CurrentEmployee ;
C. 傳回目前的資料列
若要使用 GetAncestor(0) 來傳回目前的節點,請執行下列程式碼。
DECLARE @CurrentEmployee hierarchyid
SELECT @CurrentEmployee = OrgNode FROM HumanResources.EmployeeDemo
WHERE LoginID = 'adventure-works\david0'
SELECT OrgNode.ToString() AS Text_OrgNode, *
FROM HumanResources.EmployeeDemo
WHERE OrgNode.GetAncestor(0) = @CurrentEmployee ;
D. 如果資料表不存在便傳回階層層級
GetAncestor 會傳回階層中的選取層級,即使資料表不存在也一樣。例如,下列程式碼會指定目前的員工,並且傳回目前員工之上階的 hierarchyid,但是沒有資料表的參考。
DECLARE @CurrentEmployee hierarchyid ;
DECLARE @TargetEmployee hierarchyid ;
SELECT @CurrentEmployee = '/2/3/1.2/5/3/' ;
SELECT @TargetEmployee = @CurrentEmployee.GetAncestor(2) ;
SELECT @TargetEmployee.ToString(), @TargetEmployee ;
E. 呼叫 Common Language Runtime 方法
下列程式碼片段會呼叫 GetAncestor() 方法。
this.GetAncestor(1)