无法为更新查询插入重复键错误消息

时间:2015-11-18 18:37:31

标签: sql-server

我正在尝试使用此更新查询更新数据....不插入。但我收到此错误消息。如何解决这个问题

  

Msg 2627,Level 14,State 1,Procedure   第67行BF_TR_BUDCONTRACTS_HISTORY_INSERTUPDATE违反UNIQUE   关键约束' UK_BudContractHis'。无法插入重复键   对象' dbo.BUDCONTRACTS_HISTORY'。重复的键值是(10567,   4377,228,1)。声明已经终止。

Update BUDCONTRACTS
 set    BUDCONTRACTS.VERSIONID = 1
       ,BUDCONTRACTS.STATUSID = 1
       ,BUDCONTRACTS.ImportedRecord = 1
       ,BUDCONTRACTS.CUSTOMERID = BCUST.CustomerID
       ,BUDCONTRACTS.LastModifiedUserID = 'Import'
       ,BUDCONTRACTS.LASTMODIFIEDDATETIME = GETDATE()
FROM BUDCONTRACTS BCON
INNER JOIN External_Blk_Itm_Contracts EBIC WITH(NOLOCK) ON BCON.ContractName = EBIC.ContractName  AND EBIC.ContractName = '00-000'
INNER JOIN BUDTERMINALS BT WITH(NOLOCK) ON BT.MBFTERMINALNAME = EBIC.TerminalName AND BT.TERMINALID = BCON.TERMINALID
INNER JOIN BudCustomers BCUST WITH(NOLOCK) ON BCUST.LegalName = EBIC.CustomerName AND BCUST.CustomerID = BCON.CUSTOMERID 
AND (
   (BCON.STATUSID <> 1) 
OR (BCON.ImportedRecord <> 1) 
OR (ISNULL(BCON.CUSTOMERID,'') <> ISNULL(BCUST.CustomerID,'')
))

2 个答案:

答案 0 :(得分:1)

这是编写此更新的更好方法。

Update BCON
set VERSIONID = 1
    , STATUSID = 1
    , ImportedRecord = 1
    , CUSTOMERID = BCUST.CustomerID
    , LastModifiedUserID = 'Import'
    , LASTMODIFIEDDATETIME = GETDATE()
FROM BUDCONTRACTS BCON
INNER JOIN External_Blk_Itm_Contracts EBIC ON BCON.ContractName = EBIC.ContractName  AND EBIC.ContractName = '00-000'
INNER JOIN BUDTERMINALS BT ON BT.MBFTERMINALNAME = EBIC.TerminalName AND BT.TERMINALID = BCON.TERMINALID
INNER JOIN BudCustomers BCUST ON BCUST.LegalName = EBIC.CustomerName AND BCUST.CustomerID = BCON.CUSTOMERID 
AND 
(
    BCON.STATUSID <> 1
    OR
    BCON.ImportedRecord <> 1
) 
--OR ISNULL(BCON.CUSTOMERID,'') <> ISNULL(BCUST.CustomerID,'' This is pointless here because you already joined where these values are equal

现在针对实际问题。您没有在此查询中引用dbo.BUDCONTRACTS_HISTORY,因此很明显BUDCONTACTS上有一个UPDATE触发器。这就是问题发生的地方。它可能试图在历史表中插入一行,但是已经有一行带有键值,因此它无法插入该行。如果您可以发布dbo.BUDCONTRACTS_HISTORY的触发器代码和表定义,我们可以帮助您理顺触发器。

答案 1 :(得分:0)

我遇到了同样的问题,结果是我在运行查询时返回的行数超过了1行,并且更新失败,因此更新语句中的键不足以仅更新1条记录。很好,因为我已更改了额外字段的聚集索引。