Hierarchyid(层次结构)数据类型

实例表结构

CREATE TABLE [dbo].[Emp](
    [ID] [int] IDENTITY(1,1),
    [Name] [varchar](50),
    [Org] [hierarchyid],
)

INSERT INTO Emp(Name,Org) VALUES('吴xx','/')
INSERT INTO Emp(Name,Org) VALUES('谢xx','/1/')
INSERT INTO Emp(Name,Org) VALUES('赵xx','/2/')
INSERT INTO Emp(Name,Org) VALUES('卢xx','/1/1/')
INSERT INTO Emp(Name,Org) VALUES('方xx','/1/2/')
INSERT INTO Emp(Name,Org) VALUES('詹xx','/1/3/')
INSERT INTO Emp(Name,Org) VALUES('沈xx','/2/1/')

实例基础数据

SELECT *,Org.ToString(),Org.GetLevel()
FROM Emp

  

hierarchyid方法

ToString:节点路径

--node.ToString()
SELECT *,Org.ToString()
FROM Emp

GetLevel:节点深度

--node.GetLevel()
SELECT *,Org.GetLevel()
FROM Emp

SELECT *,Org.GetLevel()
FROM Emp
WHERE Org.GetLevel() = 1

 

GetAncestor:节点N级祖先,即通过祖先节点反向获取指定级别的子节点。

--child.GetAncestor(n)
--指定节点的二级子节点
SELECT @CurrentNode = Org FROM Emp WHERE Name = '吴xx'
SELECT * FROM Emp WHERE Org.GetAncestor(2) = @CurrentNode

GetDescendant:节点子节点,大于child1且小于child2,child1/child2可为NULL。

--parent.GetDescendant(child1,child2)
--新增吴子节点,与谢/赵同级,但大于谢且小于赵。
DECLARE @Child1 hierarchyid
DECLARE @Child2 hierarchyid
SELECT @CurrentNode = Org FROM Emp WHERE Name = '吴xx'
SELECT @Child1 = Org FROM Emp WHERE Name = '谢xx'
SELECT @Child2 = Org FROM Emp WHERE Name = '赵xx'
INSERT INTO Emp(Name,Org) VALUES('于xx',@CurrentNode.GetDescendant(@Child1,@Child2))

IsDescendantOf:是否是节点的后代节点

--child.IsDescendantOf(parent)
--指定节点下的全部后代节点,包含本身
SELECT @CurrentNode = Org FROM Emp WHERE Name = '吴xx'
SELECT * FROM Emp WHERE Org.IsDescendantOf(@CurrentNode) = 1

GetReparentedValue:节点移动,节点路径从oldRoot指向newRoot

--node.GetReparentedValue(oldRoot,newRoot)
--于从指向吴子节点,更新指向赵子节点。
DECLARE @OldRoot hierarchyid
DECLARE @NewRoot hierarchyid
SELECT @CurrentNode = Org FROM Emp WHERE Name = '于xx'
SELECT @OldRoot = Org FROM Emp WHERE Name = '吴xx'
SELECT @NewRoot = Org FROM Emp WHERE Name = '赵xx'
UPDATE Emp SET Org=@CurrentNode.GetReparentedValue(@OldRoot,@NewRoot) WHERE Org = @CurrentNode

GetRoot:根节点

--hierarchyid::GetRoot()
SELECT *
FROM Emp
WHERE Org = hierarchyid::GetRoot()

 

Parse:从路径字符串转换为hierarchyid值,即编码。

--hierarchyid::Parse()
DECLARE @StringNode varchar(50)
SET @StringNode = '/1/1/'
SELECT *,Org.ToString() FROM Emp WHERE Org = hierarchyid::Parse(@StringNode)

 

posted @ 2015-09-07 21:51  平小宅  阅读(291)  评论(0编辑  收藏  举报