简体   繁体   English

为什么 MERGE 语句会抛出唯一键约束错误

[英]Why is the MERGE statement throwing a unique key constraint error

I'm attempting to run a merge statement between two tables, Table A and Table B. The statement is supposed to update records is a match exists on the designated field (Name) and to insert a record is no match exists.我正在尝试在两个表(表 A 和表 B)之间运行合并语句。该语句应该更新记录是指定字段(名称)上存在匹配项,并且插入记录不存在匹配项。

When the merge statement executes it's throwing the following error:当合并语句执行时,它会抛出以下错误:

Violation of UNIQUE KEY constraint 'AK_UniqueName'. Cannot insert duplicate key in object 'dbo.Table B'. The duplicate key value is (A. Adams).

Merge Statement, Table A, Table B and desired result follow:合并语句、表 A、表 B 和所需结果如下:

Merge Statement合并声明

BEGIN
MERGE dbo.TableB AS T
USING dbo.TableA AS S
ON T.Name LIKE S.Name
WHEN MATCHED THEN
UPDATE SET T.Lname = IsNULL(S.Lname,T.Lname),          
WHEN NOT MATCHED THEN 
INSERT (Name, Lname);
END

Table A表 A

**Name**   **Lname**
A. Adams   Adams
B. Adams   Adams

Table B表 B

**Name**   **Lname**
A. Adams   Adams
C. Adams   Adams

Desired Result (Table B after merge - with one new row)期望的结果(合并后的表 B - 一个新行)

**Name**   **Lname**
A. Adams   Adams
B. Adams   Adams
C. Adams   Adams

Typically this occurs either when there are duplicate rows in your source, or if you are updating the primary key. 通常,当源中有重复的行或正在更新主键时,就会发生这种情况。

This is why I rarely use MERGE . 这就是为什么我很少使用MERGE Instead I use separate UPDATE and INSERT statements which allows you to isolate the issue to either the insert or update step. 相反,我使用单独的UPDATEINSERT语句,使您可以将问题隔离到插入或更新步骤。

ON T.Name LIKE S.Name is unlikely to be correct. ON T.Name LIKE S.Name不太可能正确。 Please try ON T.Name = S.Name instead 请尝试ON T.Name = S.Name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM