违反主键约束错误

时间:2010-08-20 21:52:23

标签: sql-server-2008 primary-key duplicates

我正在使用SSMS 2008并尝试使用此查询插入但收到以下错误:

Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK_j5c_MasterMeasures'. Cannot insert duplicate key in object 'dbo.j5c_MasterMeasures'.
The statement has been terminated.

这是我的问题:

insert into J5C_MasterMeasures (studentid, measuredate, measureid, RIT)

select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_14
from [J5C_Measures_Sys] A
join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID 
join sysobjects so on so.name = 'J5C_Measures_Sys' 
join syscolumns sc on so.id = sc.id 
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
where so.type = 'u' and sc.name = 'score_14' and a.score_14 is not null 
AND A.STUDENTID IS NOT NULL AND A.MEASUREDATE IS NOT NULL AND B.MEASURENAME IS NOT NULL
group by a.studentid, a.measuredate, B.measurename, B.LabelName, A.score_14
--HAVING COUNT(*) > 1

奇怪的是,如果我只运行SELECT查询(没有INSERT)并包含HAVING COUNT语句,它将为>返回0条记录。所以我不知道副本的来源!

4 个答案:

答案 0 :(得分:3)

根据您之前的问题,我认为您的主键是A.studentid,A.measuredate,B.measurename。如果我错了,请纠正我。

由于除了复合主键的列之外,还要通过两个附加列B.LabelName和A.score_14进行分组,如果有任何重复项 - 可以提供它们,它们具有不同的B.LabelName值或A.score_14 - 您将违反主键约束,并且将抛出此错误。

您的数据不够独特,无法满足您的主键 - 这表明只有一行具有A.studentid,A.measuredate,B.measurename的独特组合可以存在于您的表中

答案 1 :(得分:0)

J5C_MasterMeasures表中是否已有数据?如果是这样,请确保您插入的内容尚不存在

答案 2 :(得分:0)

使用:

select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_14
  from [J5C_Measures_Sys] A
  join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID 
  join sysobjects so on so.name = 'J5C_Measures_Sys' 
  join syscolumns sc on so.id = sc.id 
  join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
 where so.type = 'u' and sc.name = 'score_14' and a.score_14 is not null 
   AND A.STUDENTID IS NOT NULL AND A.MEASUREDATE IS NOT NULL AND B.MEASURENAME IS NOT NULL
   AND NOT EXISTS(SELECT NULL
                    FROM J5C_MasterMeasures x
                   WHERE x.studentid = a.studentid
                     AND x.measuredate = a.measuredate
                     AND x.measureid = B.measurename +' '+ B.LabelName)
group by a.studentid, a.measuredate, B.measurename, B.LabelName, A.score_14

NOT EXISTS将过滤掉现有数据。

答案 3 :(得分:0)

你应该仔细检查你的HAVING测试。确保您只在GROUP BY子句中包含组成PK的列。