Maison >base de données >tutoriel mysql >Hierarchyid数据类型
以往我们在关系数据库中建立树状结构的时候,通常使用ID+ParentID来实现两条 纪录间的父子关系。但这种方式只能标示其相对位置。解决这类问题在SqlServer2005出现之前通常是采用游标来操作,但熟悉数据库内部机制的人都 知道使用游标带来的性能问题和其他问
以往我们在关系数据库中建立树状结构的时候,通常使用ID+ParentID来实现两条 纪录间的父子关系。但这种方式只能标示其相对位置。解决这类问题在SqlServer2005出现之前通常是采用游标来操作,但熟悉数据库内部机制的人都 知道使用游标带来的性能问题和其他问题是比较严重的。
到了SqlServer2005下,可以选择用CTE来做递归查询,这种方式查询比 较简练,但由于数据库内部是采用递归查询的方式,其效率依旧不高;为了能够实现既简练又高效的查询,通常的做法是增加冗余字段,比如增加一个"Path" 字段,查询时用模糊查询来进行左匹配。对Path建索引后,这种查询的效率还是相当高的,因此这种方式也是一种常规的设计方式;
SQL SERVER 2008引入了新的hierarchyid数据类型,可以用它来做本地存储并且在树层次结构中管理其位置.只用这个函数能简洁地表示层次结构中的位置.该 函数提供的一些内置的函数方法可以操作和遍历层次结构,使得存储和查询分层数据更为容易,而不需要像那样通过CTE递归来获得.
Hierarchyid类型其实是一个CLR自定义数据类型依次打开:数据库->系统数据库->master->可编程性->类型->系统数据类型->CLR数据类型->hierarchyid,可以看到该数据类型.
于hierarchyid有关的一些函数主要有:
hierarchyid 数据类型的值表示树层次结构中的位置。hierarchyid 的值具有以下属性:
非常紧凑
在具有 n 个节点的树中,表示一个节点所需的平均位数取决于平均端数(节点的平均子级数)。端数较小时 (0-7),大小约为 6*logAn 位,其中 A 是平均端数。对于平均端数为 6 级、包含 100,000 个人的组织层次结构,一个节点大约占 38 位。存储时,此值向上舍入为 40 位,即 5 字节。
按深度优先顺序进行比较
给定两个 hierarchyid 值 a 和 b,a 表示在对树进行深度优先遍历时,先找到 a,后找到 b。hierarchyid 数据类型的索引按深度优先顺序排序,在深度优先遍历中相邻的节点的存储位置也相邻。例如,一条记录的子级的存储位置与该记录的存储位置是相邻的。
支持任意插入和删除
通过使用 GetDescendant 方法,始终可以在任意给定节点的右侧、左侧或任意两个同级节点之间生成同级节点。在层次结构中插入或删除任意数目的节点时,该比较属性保持不变。大多数插 入和删除操作都保留了紧凑性属性。但是,对于在两个节点之间执行的插入操作,所产生的 hierarchyid 值的表示形式在紧凑性方面将稍微降低。
hierarchyid 数据类型具有以下局限性:
类 型为 hierarchyid 的列不会自动表示树。由应用程序来生成和分配 hierarchyid 值,使行与行之间的所需关系反映在这些值中。一些应用程序甚至可能不需要用类型为 hierarchyid 的列来表示树。可能这些值为对其他表中定义的层次结构中位置的引用。
由应用程序来管理生成和分配 hierarchyid 值时的并发情况。不能保证列中的 hierarchyid 值是唯一的,除非应用程序使用唯一键约束或应用程序自身通过自己的逻辑来强制实现唯一性。
由 hierarchyid 值表示的层次结构关系不是像外键关系那样强制实现的。可能会出现下面这种层次结构关系而且有时这种关系是合理的:A 具有子级 B,然后删除了 A,导致 B 与一条不存在的记录之间存在关系。如果这种行为不可接受,应用程序在删除父级之前必须先查询其是否有后代。
用于对分层数据进行索引的策略有两种:
深度优先
深度优先索引,子树中各行的存储位置相邻。例如,一位经理管理的所有雇员都存储在其经理的记录附近。
广度优先
广度优先将层次结构中每个级别的各行存储在一起。例如,同一经理直属的各雇员的记录存储在相邻位置。
例如下面的例子是一个职员表,数据有如下关系:
Scott
|
Mark Ravi
| |
Ben Laura Vijay Frank James
<span>Use</span> AdventureWorksLT <span>Go</span> --Scheme Creation <span>Create</span> <span>Schema</span> HumanResources <span>Go</span> --<span>Table</span> Creation <span>CREATE</span> <span>TABLE</span> HumanResources.EmployeeDemo ( OrgNode HIERARCHYID, EmployeeID <span>INT</span>, LoginID <span>VARCHAR</span>(100), Title <span>VARCHAR</span>(200), HireDate DATETIME ) <span>Go</span> --<span>Index</span> Creation <span>CREATE</span> <span>UNIQUE</span> <span>CLUSTERED</span> <span>INDEX</span> idxEmployeeDemo <span>ON</span> HumanResources.EmployeeDemo (OrgNode,EmployeeID)下面插入一些数据
SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (hierarchyid::GetRoot(), 1,<span>'adventure-works\scott'</span>, <span>'CEO'</span>, <span>'3/11/05'</span>) ; CLARE @Manager hierarchyid LECT @Manager = hierarchyid::GetRoot() <span>FROM</span> HumanResources.EmployeeDemo; SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(<span>NULL</span>,<span>NULL</span>), 2, <span>'adventure-works\Mark'</span>, <span>'CTO'</span>, <span>'4/05/07'</span>) CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid LECT @Manager = hierarchyid::GetRoot() <span>FROM</span> HumanResources.EmployeeDemo; lect @FirstChild = @Manager.GetDescendant(<span>NULL</span>,<span>NULL</span>) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(@FirstChild,<span>NULL</span>), 3, <span>'adventure-works\ravi'</span>, <span>'Director Marketing'</span>, <span>'4/08/07'</span>) Insert the <span>First</span> Descendant <span>of</span> a Child Node CLARE @Manager hierarchyid LECT @Manager = <span>CAST</span>(<span>'/1/'</span> <span>AS</span> hierarchyid) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(<span>NULL</span>, <span>NULL</span>),45, <span>'adventure-works\Ben'</span>,<span>'Application Developer'</span>, <span>'6/11/07'</span>) ; Insert the <span>Second</span> Descendant <span>of</span> a Child Node CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid LECT @Manager = <span>CAST</span>(<span>'/1/'</span> <span>AS</span> hierarchyid) LECT @FirstChild = @Manager.GetDescendant(<span>NULL</span>,<span>NULL</span>) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(@FirstChild, <span>NULL</span>),55, <span>'adventure-works\Laura'</span>,<span>'Trainee Developer'</span>, <span>'6/11/07'</span>) ; Insert the <span>first</span> node who <span>is</span> the Descendant <span>of</span> Director Marketing CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid LECT @Manager = <span>CAST</span>(<span>'/2/'</span> <span>AS</span> hierarchyid) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(<span>NULL</span>, <span>NULL</span>),551, <span>'adventure-works\frank'</span>,<span>'Trainee Sales Exec.'</span>, <span>'12/11/07'</span>) ; Insert the <span>second</span> node who <span>is</span> the Descendant <span>of</span> Director Marketing CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid LECT @Manager = <span>CAST</span>(<span>'/2/'</span> <span>AS</span> hierarchyid) LECT @FirstChild = @Manager.GetDescendant(<span>NULL</span>,<span>NULL</span>) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(@FirstChild, <span>NULL</span>),531, <span>'adventure-works\vijay'</span>,<span>'Manager Industrial Sales'</span>, <span>'12/09/06'</span>) ; Insert the third node who <span>is</span> the Descendant <span>of</span> Director Marketing <span>in</span> <span>between</span> 2 existing descendants CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid CLARE @SecondChild hierarchyid LECT @Manager = <span>CAST</span>(<span>'/2/'</span> <span>AS</span> hierarchyid) LECT @FirstChild = @Manager.GetDescendant(<span>NULL</span>,<span>NULL</span>) LECT @SecondChild = @Manager.GetDescendant(@FirstChild,<span>NULL</span>) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(@FirstChild, @SecondChild),543, <span>'adventure-works\james'</span>,<span>'Manager Consumer Sales'</span>, <span>'12/04/06'</span>) ;
<span>DECLARE</span> @TID hierarchyid <span>SELECT</span> @TID=OrgNode <span>FROM</span> HumanResources.EmployeeDemo <span>WHERE</span> title=<span>'cto'</span> <span>SELECT</span> *, OrgNode.GetLevel() <span>as</span> 层次,OrgNode.ToString() <span>as</span> 路径 <span>FROM</span> HumanResources.EmployeeDemo <span>WHERE</span> @TID.IsDescendantOf(OrgNode)=1 <span>SELECT</span> *, OrgNode.GetLevel() <span>as</span> 层次,OrgNode.ToString() <span>as</span> 路径 <span>FROM</span> HumanResources.EmployeeDemo <span>WHERE</span> OrgNode.IsDescendantOf(@TID)=1
<img title="image" alt="image" src="http://www.68idc.cn/help/uploads/allimg/151109/1024114a8-2.png" style="max-width:90%" style="max-width:90%" />下面另外附几个操作的存储过程:
<span>SET</span> QUOTED_IDENTIFIER <span>ON</span> <span>GO</span> --<span>Use</span> Serializable <span>Transaction</span> <span>CREATE</span> <span>PROCEDURE</span> [dbo].[AddEmployee](@ManagerID hierarchyid, @EmpID <span>int</span>, @LogID <span>varchar</span>(100), @JobTitle <span>as</span> <span>varchar</span>(200), @JoiningDate datetime) <span>AS</span> <span>BEGIN</span> <span>DECLARE</span> @LastChild hierarchyid <span>SET</span> <span>TRANSACTION</span> <span>ISOLATION</span> <span>LEVEL</span> SERIALIZABLE <span>BEGIN</span> <span>TRANSACTION</span> <span>SELECT</span> @LastChild = <span>Max</span>(OrgNode) <span>From</span> HumanResources.EmployeeDemo <span>WHERE</span> OrgNode = @ManagerID INSERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) <span>VALUES</span>(@LastChild, @EmpID,@LogID , @JobTitle, @JoiningDate) <span>COMMIT</span> <span>END</span> ;
移动层级关系
<span>CREATE</span> <span>PROCEDURE</span> MoveOrg(@oldMgr nvarchar(256), @newMgr nvarchar(256) ) <span>AS</span> <span>BEGIN</span> <span>DECLARE</span> @nold HierarchyID <span>DECLARE</span> @nnew HierarchyID <span>SELECT</span> @nold = OrgNode <span>FROM</span> HumanResources.EmployeeDemo <span>WHERE</span> LoginID = @oldMgr ; <span>SET</span> <span>TRANSACTION</span> <span>ISOLATION</span> <span>LEVEL</span> SERIALIZABLE <span>BEGIN</span> <span>TRANSACTION</span> <span>SELECT</span> @nnew = OrgNode <span>FROM</span> HumanResources.EmployeeDemo <span>WHERE</span> LoginID = @newMgr ; <span>SELECT</span> @nnew = @nnew.GetDescendant(<span>max</span>(OrgNode), <span>NULL</span>) <span>FROM</span> HumanResources.EmployeeDemo <span>WHERE</span> OrgNode.GetAncestor(1)=@nnew ; <span>UPDATE</span> HumanResources.EmployeeDemo <span>SET</span> OrgNode = OrgNode.GetReparentedValue(@nold, @nnew) <span>WHERE</span> @nold.IsDescendantOf(OrgNode) = 1 <span>COMMIT</span> <span>TRANSACTION</span> <span>END</span>
<span>Create</span> <span>Function</span> GetMyMaxChild(@ManagerID <span>as</span> BigInt) <span>Returns</span> HierarchyID <span>BEGIN</span> <span>Declare</span> @ManagerNode HierarchyID <span>Declare</span> @MaxChild HierarchyID --<span>Get</span> the ManagerNode <span>Select</span> @ManagerNode = OrgNode <span>from</span> HumanResources.EmployeeDemo <span>Where</span> EmployeeID = @ManagerID --<span>Get</span> the <span>Max</span> Child <span>Select</span> @MaxChild = <span>Max</span>(OrgNode) <span>from</span> HumanResources.EmployeeDemo <span>Where</span> OrgNode.GetAncestor(1) = @ManagerNode --<span>Return</span> the <span>Value</span> <span>RETURN</span> @MaxChild <span>END</span>
http://msdn.microsoft.com/zh-cn/library/bb677173.aspx
http://nibblersrevenge.cluss.de/archive/2009/05/31/how-to-use-hierarchyid-in-linqtosql-or-entity-framework-mssql.aspx
http://www.cnblogs.com/downmoon/archive/2011/05/03/2035259.html
Use AdventureWorksLT Go --Scheme Creation Create Schema HumanResources Go --Table Creation CREATE TABLE HumanResources.EmployeeDemo ( OrgNode HIERARCHYID, EmployeeID INT, LoginID VARCHAR(100), Title VARCHAR(200), HireDate DATETIME ) Go --Index Creation CREATE UNIQUE CLUSTERED INDEX idxEmployeeDemo ON HumanResources.EmployeeDemo (OrgNode,EmployeeID)
SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (hierarchyid::GetRoot(), 1,'adventure-works\scott', 'CEO', '3/11/05') ; CLARE @Manager hierarchyid LECT @Manager = hierarchyid::GetRoot() FROM HumanResources.EmployeeDemo; SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(NULL,NULL), 2, 'adventure-works\Mark', 'CTO', '4/05/07') CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid LECT @Manager = hierarchyid::GetRoot() FROM HumanResources.EmployeeDemo; lect @FirstChild = @Manager.GetDescendant(NULL,NULL) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(@FirstChild,NULL), 3, 'adventure-works\ravi', 'Director Marketing', '4/08/07') Insert the First Descendant of a Child Node CLARE @Manager hierarchyid LECT @Manager = CAST('/1/' AS hierarchyid) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(NULL, NULL),45, 'adventure-works\Ben','Application Developer', '6/11/07') ; Insert the Second Descendant of a Child Node CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid LECT @Manager = CAST('/1/' AS hierarchyid) LECT @FirstChild = @Manager.GetDescendant(NULL,NULL) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(@FirstChild, NULL),55, 'adventure-works\Laura','Trainee Developer', '6/11/07') ; Insert the first node who is the Descendant of Director Marketing CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid LECT @Manager = CAST('/2/' AS hierarchyid) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(NULL, NULL),551, 'adventure-works\frank','Trainee Sales Exec.', '12/11/07') ; Insert the second node who is the Descendant of Director Marketing CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid LECT @Manager = CAST('/2/' AS hierarchyid) LECT @FirstChild = @Manager.GetDescendant(NULL,NULL) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(@FirstChild, NULL),531, 'adventure-works\vijay','Manager Industrial Sales', '12/09/06') ; Insert the third node who is the Descendant of Director Marketing in between 2 existing descendants CLARE @Manager hierarchyid CLARE @FirstChild hierarchyid CLARE @SecondChild hierarchyid LECT @Manager = CAST('/2/' AS hierarchyid) LECT @FirstChild = @Manager.GetDescendant(NULL,NULL) LECT @SecondChild = @Manager.GetDescendant(@FirstChild,NULL) SERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) LUES (@Manager.GetDescendant(@FirstChild, @SecondChild),543, 'adventure-works\james','Manager Consumer Sales', '12/04/06') ;
DECLARE @TID hierarchyid SELECT @TID=OrgNode FROM HumanResources.EmployeeDemo WHERE title='cto' SELECT *, OrgNode.GetLevel() as 层次,OrgNode.ToString() as 路径 FROM HumanResources.EmployeeDemo WHERE @TID.IsDescendantOf(OrgNode)=1 SELECT *, OrgNode.GetLevel() as 层次,OrgNode.ToString() as 路径 FROM HumanResources.EmployeeDemo WHERE OrgNode.IsDescendantOf(@TID)=1
SET QUOTED_IDENTIFIER ON GO --Use Serializable Transaction CREATE PROCEDURE [dbo].[AddEmployee](@ManagerID hierarchyid, @EmpID int, @LogID varchar(100), @JobTitle as varchar(200), @JoiningDate datetime) AS BEGIN DECLARE @LastChild hierarchyid SET TRANSACTION ISOLATION LEVEL SERIALIZABLE BEGIN TRANSACTION SELECT @LastChild = Max(OrgNode) From HumanResources.EmployeeDemo WHERE OrgNode = @ManagerID INSERT HumanResources.EmployeeDemo (OrgNode, EmployeeID, LoginID, Title, HireDate) VALUES(@LastChild, @EmpID,@LogID , @JobTitle, @JoiningDate) COMMIT END ;
CREATE PROCEDURE MoveOrg(@oldMgr nvarchar(256), @newMgr nvarchar(256) ) AS BEGIN DECLARE @nold HierarchyID DECLARE @nnew HierarchyID SELECT @nold = OrgNode FROM HumanResources.EmployeeDemo WHERE LoginID = @oldMgr ; SET TRANSACTION ISOLATION LEVEL SERIALIZABLE BEGIN TRANSACTION SELECT @nnew = OrgNode FROM HumanResources.EmployeeDemo WHERE LoginID = @newMgr ; SELECT @nnew = @nnew.GetDescendant(max(OrgNode), NULL) FROM HumanResources.EmployeeDemo WHERE OrgNode.GetAncestor(1)=@nnew ; UPDATE HumanResources.EmployeeDemo SET OrgNode = OrgNode.GetReparentedValue(@nold, @nnew) WHERE @nold.IsDescendantOf(OrgNode) = 1 COMMIT TRANSACTION END
Create Function GetMyMaxChild(@ManagerID as BigInt) Returns HierarchyID BEGIN Declare @ManagerNode HierarchyID Declare @MaxChild HierarchyID --Get the ManagerNode Select @ManagerNode = OrgNode from HumanResources.EmployeeDemo Where EmployeeID = @ManagerID --Get the Max Child Select @MaxChild = Max(OrgNode) from HumanResources.EmployeeDemo Where OrgNode.GetAncestor(1) = @ManagerNode --Return the Value RETURN @MaxChild END