我正在尝试执行一个存储过程,该过程将一个新客户插入到客户表中,然后在关联表中与现有客户创建新的关联。
这必须作为一个过程来完成。
我违反了在Customer1Id,Customer2Id和AssociationType之间的关联表上的唯一约束(这也是一个引用类型引用表的ID)。两个客户可以多次关联,但不能通过相同的关联类型关联。这是演示此问题的表格:
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9uMmx1by5wbmcifQ==” alt =“关联表”>“ >>
存储过程如下:
CREATE PROC 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 GO
执行查询为(带有注释):
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
并且执行中的以下错误是:
((影响1行)消息2627,级别14,状态1,过程usp_CreateNewCustomer_Association,第22行违反UNIQUE KEY约束'UC_Associations'。无法在对象'dbo.Associations'中插入重复的密钥。重复的键值为(14、3、43)。该语句已终止。
我对使用唯一性约束不是很熟悉(这很明显),但是我不允许放弃唯一性约束,所以如果有人可以建议我如何纠正这个唯一性约束,我将不胜感激。
我正在尝试执行一个存储过程,该过程将一个新客户插入到客户表中,然后在关联表中与现有客户创建新的关联。这个...
您正在尝试使用相同的身份更新所有关联
您的UPDATE语句始终尝试更新所有列,因为您没有WHERE条件。