实例表结构
CREATE TABLE [dbo].[Emp]( [ID] [int] IDENTITY(1,1), [Name] [varchar](50), [Org] [hierarchyid], ) INSERT INTO tempdb..Emp(Name,Org) VALUES(‘吴xx‘,‘/‘) INSERT INTO tempdb..Emp(Name,Org) VALUES(‘谢xx‘,‘/1/‘) INSERT INTO tempdb..Emp(Name,Org) VALUES(‘赵xx‘,‘/2/‘) INSERT INTO tempdb..Emp(Name,Org) VALUES(‘卢xx‘,‘/1/1/‘) INSERT INTO tempdb..Emp(Name,Org) VALUES(‘方xx‘,‘/1/2/‘) INSERT INTO tempdb..Emp(Name,Org) VALUES(‘詹xx‘,‘/1/3/‘) INSERT INTO tempdb..Emp(Name,Org) VALUES(‘沈xx‘,‘/2/1/‘)
实例基础数据
SELECT *,Org.ToString(),Org.GetLevel() FROM tempdb..Emp
hierarchyid方法引用
ToString:节点路径
--node.ToString() SELECT *,Org.ToString() FROM tempdb..Emp
GetLevel:节点深度
--node.GetLevel() SELECT *,Org.GetLevel() FROM tempdb..Emp SELECT *,Org.GetLevel() FROM tempdb..Emp WHERE Org.GetLevel() = 1
GetAncestor:节点N级祖先,即通过祖先节点反向获取指定级别的子节点。
--child.GetAncestor(n) --指定节点下的二级子节点 SELECT @CurrentNode = Org FROM tempdb..Emp WHERE Name = ‘吴xx‘ SELECT * FROM tempdb..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 tempdb..Emp WHERE Name = ‘吴xx‘ SELECT @Child1 = Org FROM tempdb..Emp WHERE Name = ‘谢xx‘ SELECT @Child2 = Org FROM tempdb..Emp WHERE Name = ‘赵xx‘ INSERT INTO tempdb..Emp(Name,Org) VALUES(‘于xx‘,@CurrentNode.GetDescendant(@Child1,@Child2))
IsDescendantOf:是否是节点的后代节点
--child.IsDescendantOf(parent) --指定节点下的全部后代节点,包含本身 SELECT @CurrentNode = Org FROM tempdb..Emp WHERE Name = ‘吴xx‘ SELECT * FROM tempdb..Emp WHERE Org.IsDescendantOf(@CurrentNode) = 1
GetReparentedValue:当前节点变更新路径,从oldRoot指向newRoot
--node.GetReparentedValue(oldRoot,newRoot) --于从指向吴子节点,更新指向赵子节点。 DECLARE @OldRoot hierarchyid DECLARE @NewRoot hierarchyid SELECT @CurrentNode = Org FROM tempdb..Emp WHERE Name = ‘于xx‘ SELECT @OldRoot = Org FROM tempdb..Emp WHERE Name = ‘吴xx‘ SELECT @NewRoot = Org FROM tempdb..Emp WHERE Name = ‘赵xx‘ UPDATE tempdb..Emp SET [email protected](@OldRoot,@NewRoot) WHERE Org = @CurrentNode
GetRoot:根节点
--hierarchyid::GetRoot() SELECT * FROM tempdb..Emp WHERE Org = hierarchyid::GetRoot()
Parse:从路径字符串转换为hierarchyid值,即重新编码。
--hierarchyid::Parse() DECLARE @StringNode varchar(50) SET @StringNode = ‘/1/1/‘ SELECT *,Org.ToString() FROM tempdb..Emp WHERE Org = hierarchyid::Parse(@StringNode)
时间: 2024-10-11 05:32:23