Hierarchy data type in sql server has duplicate
I have the following table
ChildID ParentID
1 0
1 2
4 3
1 4
2 6
4 8
as base for the child to parent relationship
Running query:
CREATE TABLE #Org (
OrgNode [hierarchyid],
ChildID int,
ParentID int
CONSTRAINT PK_OrgNode PRIMARY KEY CLUSTERED (OrgNode));
CREATE TABLE #Child (
ChildID int,
ParentID int,
Num int);
CREATE CLUSTERED INDEX tmpind ON #Child(ParentID, ChildID);
INSERT INTO #Child
SELECT DISTINCT
ChildID = ChildID,
ParentID = ParentID,
Num = ROW_NUMBER() OVER (PARTITION BY ParentID ORDER BY ParentID)
FROM #tmpEntity;
The result is as expected:
ChildID ParentID Num
1 0 1
1 2 1
4 3 1
1 4 1
2 6 1
4 8 1
when running the next step
WITH paths(path, ChildID)
AS
(SELECT hierarchyid::GetRoot() AS OrgNode, ChildID
FROM #Child AS C
WHERE ParentID = 0
UNION ALL
SELECT CAST(p.path.ToString() + CAST(C.Num AS varchar(30)) + '/' AS hierarchyid), C.ChildID
FROM #Child AS C
JOIN paths AS p ON C.ParentID = P.ChildID)
INSERT #Org (OrgNode, O.ChildID, O.ParentID)
SELECT P.path, O.ChildID, O.ParentID
FROM #tmpEntity AS O
JOIN Paths AS P ON O.ChildID = P.ChildID
OPTION (maxrecursion 0)
GO
it throws an error now
"Msg 2627, Level 14, State 1, Line 170 Violation of PRIMARY KEY constraint 'PK_OrgNode'. Cannot insert duplicate key in object 'dbo.#Org'. The duplicate key value is (0x). The statement has been terminated."
Can anyone help or see where the bug is? Thanks