发生唯一键违规时返回行

问题描述 投票:0回答:2

是否有可能返回记录,导致MSSQL中的唯一密钥冲突,插入数据时?

c# sql-server
2个回答
0
投票

试试这个架构

select * from 
(
   --query used for your insert

) f1
where exists 
(
   select * from tablewhereyouwantinsert f2
   where f1.key1=f2.key1 and f1.key2=f2.key2 ---- keys used into your unique key violation

)

0
投票

您可以使用MERGE使用单个语句有条件地插入或检索数据库中的行。

不幸的是,为了获得检索操作,我们必须触摸现有的行,我假设这是可以接受的,并且您将能够构建一个低影响的“No-Op”UPDATE,如下所示:

create table T (ID int not null primary key, Col1 varchar(3) not null)
insert into T(ID,Col1) values (1,'abc')

;merge T t
using (values (1,'def')) s(ID,Col1)
on t.ID = s.ID
when matched then update set Col1 = t.Col1
when not matched then insert (ID,Col1) values (s.ID,s.Col1)
output inserted.*,$action;

这会产生:

ID          Col1 $action
----------- ---- ----------
1           abc  UPDATE

包括$action列可以帮助你知道这是一个现有的行,而不是insert成功的(1,def)

© www.soinside.com 2019 - 2024. All rights reserved.