SQL Flow Field Guide

hierarchyid.GetAncestor

Catalog support for SQL Server 2022 (16.x) and 2025 (17.x)

tree navigation GetAncestor

What changes

Input
hierarchyid instance and arguments
Output or change
hierarchyid
Return type
SQL Server return type:hierarchyid CLR return type:SqlHierarchyId

Syntax at a glance

child.GetAncestor ( n )

Work example

Find a node's ancestor at a chosen number of levels above it.

Check the requested level against GetLevel and handle a null result when the count goes above the root.

Check your work GetAncestor(0) returns the current node and a count larger than the node depth returns null.

Practice SQL

Open in SQL Flow
DECLARE @node hierarchyid = hierarchyid::Parse('/4/2/'); SELECT @node.GetAncestor(1).ToString() AS parent_path;

Open Microsoft Learn for full syntax, permissions, and details for your version.