我有一个名为tb_Section的表。它旨在支持n级层次结构。每行有一个ParentSetionId指向另一行的SectionId在父/子关系的情况下。在父项中使用hierarchyId子项关系
现在,我有一个过程,我必须将这些节逐一复制到另一个表中,保持层次结构完整。我通过如下使用顺序排列的部分:
Select
s.SectionId,
s.ParentSectionId,
s.SectionName
From
tb_Section s
Where
s.TemplateId = 123
Order By
Convert(hierarchyid, '/' + cast(sec.ParentSectionId as varchar)+ '/')
我在一个不是Temptable插入这些和被一个在另一个表中插入各段中的一个。这工作正常。但是在申请上线后,报道了一个问题。
首先创建的所有部分作为家长部分,然后逐一编辑他们,让他们的孩子其他部分(使用的最艰难的方式:/)用户的部分层次如下:
Super-Parent
Parent1
Child1
Child2
Parent2
Child3
Child4
在这种情况下,上述查询按顺序返回以下行。
SuperParent
Child1
Child2
Parent1
Child3
Child4
Parent2
而不是正常的情况下,应该在此
SuperParent
Parent1
Child1
Child2
Parent2
Child3
Child4
对此任何帮助吗?我似乎无法找到发生这种情况的原因。
UPDATE
下面是SQL脚本,让孩子先插入。
CREATE TABLE tb_Section(
SectionId BIGINT NOT NULL PRIMARY KEY
,ParentSectionId BIGINT
,SectionName NVARCHAR(50) NOT NULL
);
INSERT INTO tb_Section(SectionId,ParentSectionId,SectionName) VALUES (SectionId,ParentSectionId,N'SectionName');
INSERT INTO tb_Section(SectionId,ParentSectionId,SectionName) VALUES (686772,686776,N'Child 1');
INSERT INTO tb_Section(SectionId,ParentSectionId,SectionName) VALUES (686773,686776,N'Child 2');
INSERT INTO tb_Section(SectionId,ParentSectionId,SectionName) VALUES (686774,686777,N'Child 3');
INSERT INTO tb_Section(SectionId,ParentSectionId,SectionName) VALUES (686775,686777,N'Child 4');
INSERT INTO tb_Section(SectionId,ParentSectionId,SectionName) VALUES (686776,686778,N'Parent 1');
INSERT INTO tb_Section(SectionId,ParentSectionId,SectionName) VALUES (686777,686778,N'Parent 2');
INSERT INTO tb_Section(SectionId,ParentSectionId,SectionName) VALUES (686778,NULL,N'Super-Parent');
下面是结果我用上面的查询返回HIERARCHYID
+-----------+-----------------+---------------+--------------+----------------+
| SectionId | ParentSectionId | SectionTypeId | SectionName | hierarchy |
+-----------+-----------------+---------------+--------------+----------------+
| 686778 | NULL | 1 | Super-Parent | NULL |
| 686772 | 686776 | 2 | Child 1 | 0xF800298C6620 |
| 686773 | 686776 | 2 | Child 2 | 0xF800298C6620 |
| 686774 | 686777 | 2 | Child 3 | 0xF800298C6660 |
| 686775 | 686777 | 2 | Child 4 | 0xF800298C6660 |
| 686776 | 686778 | 2 | Parent 1 | 0xF800298C66A0 |
| 686777 | 686778 | 2 | Parent 2 | 0xF800298C66A0 |
+-----------+-----------------+---------------+--------------+----------------+
你可以看到,层次不同的是,这里的孩子资料的家长表示前面。我希望这个样本数据有帮助。
这是一个很好的开始。 http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ –
原始表格数据的示例将很有用 –
为什么不使用hierachid键入https://msdn.microsoft.com/en-us/library/bb677173.aspx –