违反唯一约束

Violation of Unique Constraint

我正在尝试执行将新客户插入客户 table 并随后在关联 table 中创建与现有客户的新关联的存储过程。

这必须作为一个过程来完成。

我违反了 Customer1Id、Customer2Id 和 AssociationType 的关联 table 的唯一约束(这也是一个引用 table 类型的 ID)。两个客户可以相互关联多次,但不是通过相同的关联类型。这是 table 来证明这一点:

存储过程如下:


CREATE PROCEDURE usp_CreateNewCustomer_Association
    @CustomerType INT,
    @FirstName VARCHAR(30),
    @LastName VARCHAR(30),
    @CompanyName VARCHAR(40) = NULL, 
    @AddressLine1 VARCHAR(30),
    @AddressLine2 VARCHAR(20) = NULL,
    @City VARCHAR(20),
    @Country VARCHAR(30),
    @DOB DATE = NULL,
    @Customer2Id INT,
    @AssociationType INT
AS
BEGIN
    INSERT INTO Customers
(CustomerType, FirstName, LastName, CompanyName, AddressLine1, AddressLine2, City, Country, DOB)
    VALUES (@CustomerType, @FirstName, @LastName, @CompanyName, @AddressLine1, @AddressLine2, @City, @Country, @DOB)

    UPDATE Associations
    SET Customer1Id = @@IDENTITY,
        Customer2Id = @Customer2Id,
        AssociationType = @AssociationType
END 

执行查询是(带注释):

EXEC usp_CreateNewCustomer_Association
         @CustomerType = 1,         -- Personal Customer code = '1'
         @FirstName = 'Henry',
         @LastName = 'Godfrey',
         @AddressLine1 = 'Tripton Heights',
         @AddressLine2 = 'Broadspoke',
         @City = 'Sydney',
         @Country = 'Australia',
         @Customer2Id = 3,          -- There is an existing customer with the ID '3'
         @AssociationType = 43      -- Association type 43 means 'Developer' as in Customer (num) is the developer for customer 3

我收到这个错误:

Msg 2627, Level 14, State 1, Procedure usp_CreateNewCustomer_Association, Line 22
Violation of UNIQUE KEY constraint 'UC_Associations'. Cannot insert duplicate key in object 'dbo.Associations'. The duplicate key value is (14, 3, 43).

我不太熟悉使用唯一约束(这可能很明显),但不允许我删除唯一约束,因此如果有人可以建议我如何更正此问题,我将不胜感激。

您正在尝试更新具有相同身份的所有关联

UPDATE Associations
SET Customer1Id = @@IDENTITY,
    Customer2Id = @Customer2Id,
    AssociationType = @AssociationType

没有where条件

编辑:

我觉得@Larnu的发言很重要,所以引用它

I recommend against @@INDENTITY; it is not limited to the current scope. Either use SCOPE_IDENTITY or an OUTPUT clause to get the value. Otehrwise you could easily end up with an identity value from a different scope. – @Larnu

您的 UPDATE 语句总是尝试更新所有列,因为您没有 WHERE 条件。

您应该将 UPDATE 语句更改为包含 WHERE 条件,或者将其更改为 INSERT - 因为我不完全理解这应该如何仅与 UPDATE 语句一起工作。