使用Varchar列的Hierarchyid数据类型

时间:2017-07-05 14:58:30

标签: sql sql-server tsql

在表格中,有一个像DepartmentCode和ParentDepartmentCode这样的列  是varchar(5)列。 DepartmentCode的样本值类似于1,123,ABC,DEF

我正在尝试使用上面创建HierarchyId数据类型列。当创建层次结构为/ 1/123时,它很好,但是当创建层次结构为/ 1 / ABC时,它会抛出错误,如下所示。所以我想我们不能在HierarchyId中使用字符串数据吗?

CREATE TABLE [dbo].[Test_Department](
[GLDHierarchyID] hierarchyid NOT NULL
)
insert into Test_Department([GLDHierarchyID]) select hierarchyid::GetRoot();
insert into Test_Department([GLDHierarchyID]) select hierarchyid::Parse('/'+ 
cast(1 as varchar(4))+'/');
select [GLDHierarchyID].ToString() from [Test_Department]

--This works good
Declare @testData varchar(3)='123'
Declare @hiearchy hierarchyid 
SELECT @hiearchy=[GLDHierarchyID] FROM [Test_Department] where 
[GLDHierarchyID].GetLevel()=1
INSERT INTO Test_Department([GLDHierarchyID]) 
SELECT  
Case when try_parse(@testData as int)>0 then 
hierarchyid::Parse(@hiearchy.ToString()  + cast(cast(@testData as int) as 
varchar(5))+'/')
else hierarchyid::Parse(@hiearchy.ToString() + cast(@testData as varchar(5)) 
+'/')
end as GLDHierarchyID
--select [GLDHierarchyID].ToString() from [Test_Department]

--This does not work
Declare @testData varchar(3)='ABC'
Declare @hiearchy hierarchyid 
SELECT @hiearchy=[GLDHierarchyID] FROM [Test_Department] where 
[GLDHierarchyID].GetLevel()=1
INSERT INTO Test_Department([GLDHierarchyID]) 
SELECT  
Case when try_parse(@testData as int)>0 then 
hierarchyid::Parse(@hiearchy.ToString()  + cast(cast(@testData as int) as 
varchar(5))+'/')
else hierarchyid::Parse(@hiearchy.ToString() + cast(@testData as varchar(5)) 
+'/')
end as GLDHierarchyID
--select [GLDHierarchyID].ToString() from [Test_Department]





Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or 
aggregate "hierarchyid": 
Microsoft.SqlServer.Types.HierarchyIdException: 24001: SqlHierarchyId.Parse 
failed because the input string '/1/ABC/' is not a valid string 
representation of a SqlHierarchyId node.
Microsoft.SqlServer.Types.HierarchyIdException: 
at Microsoft.SqlServer.Types.OrdPath.InitFromString(String chDottedString)
at Microsoft.SqlServer.Types.SqlHierarchyId.Parse(SqlString input)
.

1 个答案:

答案 0 :(得分:0)

documentation说:

  

斜杠开始表示,只访问根的路径由单个斜杠表示。对于根下面的级别,每个标签被编码为由点分隔的整数序列。通过比较按字典顺序由点分隔的整数序列来执行子项之间的比较。每个级别后跟一个斜线。因此,斜线将父母与子女分开。

所以,你可以拥有像/1/1.2/3.17/这样的东西,但这样的东西就像它变得异国情调一样。

我很幸运做了一个以斜线分隔的ID列表。它具有自我记录的额外好处(即您可以自己重新创建路径)。