2

我正在编写一条 SQL 语句来从临时表中更新 SQL 中的表。我不断收到此错误消息:Cannot insert duplicate key row in object with unique index 'SAXXIRPT'

这是我的更新声明:

Update dbo.sat_ser_rpt_itm
SET itm_key_cd = n.itm_key_cd,
  itm_typ_cd  = n.itm_typ_cd,
  ser_id  = n.ser_id ,
  as_of_dt = n.as_of_dt,
  ocrn_nr  = n.ocrn_nr ,
  id_rssd = n.id_rssd,
  ocrn_day_txt = n.ocrn_day_txt ,
  ocrn_dt = n.ocrn_dt ,
  hol_flg = n.hol_flg ,
  ocrn_val_nr = n.ocrn_val_nr 
  from #LookupTable n
  on sat_ser_rpt_itm.id_rssd = n.id_rssd 
AND sat_ser_rpt_itm.as_of_dt = n.as_of_dt 
AND sat_ser_rpt_itm.ser_id = n.ser_id 
and sat_ser_rpt_itm.itm_typ_cd = n.itm_typ_cd 
and sat_ser_rpt_itm.ocrn_nr = n.ocrn_nr 
where t.id_rssd is not null and  t.as_of_dt is not null  and  t.ser_id is not null and  t.itm_typ_cd is not null and t.ocrn_nr is not null  

这些是我的索引(聚集):

id_rssd, as_of_dt, ser_id, itm_key_cd and ocrn_nr

是什么导致此错误消息?

4

2 回答 2

2

错误消息中没有太多歧义:您在某处设置了重复项

  1. 该组合已存在,您正在尝试再次插入它或
  2. 它不存在,并且您正在使用相同的组合更新多行或
  3. 重叠:该组合已经存在,并且您正在使用相同的组合更新多行。

我认为导致您出现此问题的问题 Updating multiple rows with same combination

我不确定表dbo.sat_ser_rpt_itm的主键是什么

通过加入两个表(dbo.sat_ser_rpt_itm,#lookup_table)尝试这样

Update itm
SET 
   //itm_key_cd = n.itm_key_cd,
   //ser_id = n.ser_id
  itm_typ_cd  = n.itm_typ_cd,
  //as_of_dt = n.as_of_dt,
  //ocrn_nr  = n.ocrn_nr ,
 //id_rssd = n.id_rssd,
  ocrn_day_txt = n.ocrn_day_txt ,
  ocrn_dt = n.ocrn_dt ,
  hol_flg = n.hol_flg ,
  ocrn_val_nr = n.ocrn_val_nr 
  FROM dbo.sat_ser_rpt_itm itm 
  INNER JOIN #LookupTable n
  ON ..................  ( it could be itm.id_rssd = n.id_rssd OR itm.as_of_dt = n.as_of_dt  OR
                           OR  itm.ser_id = n.ser_id OR itm.itm_key_cd = n.itm_key_cd OR 
                            itm.ocrn_nr = n.ocrn_nr )

  WHERE t.id_rssd is not null AND  t.as_of_dt is not null  
  AND  t.ser_id is not null AND  t.itm_typ_cd is not null AND t.ocrn_nr is not null 
于 2012-11-08T12:39:13.670 回答
0

回答很晚了,但是您的问题可能很简单,并且您的关键约束(您没有显示出来,但这可能是您的问题)正在做它应该做的事情。

当您将更新语句数据组合到受约束的键中时,如果您按该键进行选择,您会发现您返回一个结果。解决方案是首先通过键选择并查看它是否存在,然后根据需要更新它,xor 删除重复项,或者执行其他操作。

所以看看被违反的键约束——消息应该说'重复键是(东西等......)选择,看看你是否不试图将现有项目更改为另一个现有项目。

干杯,丹尼尔·韦斯科特

于 2014-10-30T18:11:24.063 回答