违反PRIMARY KEY约束“ PK_OrgNode”。无法在对象'dbo。#Org'中插入重复密钥。重复键值为(0x)

时间:2019-05-16 13:01:18

标签: sql-server

sql server中的层次结构数据类型重复

我有下表

ChildID ParentID
1   0
1   2
4   3
1   4
2   6
4   8

作为孩子与父母之间关系的基础

运行查询:

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;

结果符合预期:

ChildID ParentID    Num
1   0   1
1   2   1
4   3   1
1   4   1
2   6   1
4   8   1

进行下一步时

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 

现在会引发错误

  

“ Msg 2627,级别14,状态1,第170行违反主键   约束'PK_OrgNode'。无法在对象中插入重复键   'dbo。#Org'。重复的键值为(0x)。该声明已经   终止。”

任何人都可以帮助或查看错误的地方吗? 谢谢

0 个答案:

没有答案