Sql server 更新表给出主键冲突错误

Sql server 更新表给出主键冲突错误,sql-server,database,join,Sql Server,Database,Join,我有两张桌子 create table #temp(id int,rid int) insert into #temp select 1,1 union all select 2,1 union all select 3,1 select * from #temp drop table #temp1 create table #temp1(id int, nid int,PRIMARY KEY CLUSTERED ( id asc,nid asc )) insert into #temp1

我有两张桌子

create table #temp(id int,rid int)
insert into #temp
select 1,1
union all
select 2,1
union all
select 3,1

select * from #temp

drop table #temp1
create table #temp1(id int, nid int,PRIMARY KEY CLUSTERED
(
id asc,nid asc
))

insert into #temp1
select 1,10
union all
select 2,10
union all
select 2,11
union all
select 3,10
以下是两个结果集:

id  rid
1   1
2   1
3   1

id  nid
1   10
2   10
2   11
3   10
我想通过匹配两个表中的id字段,用temp表的rid字段中的值更新temp1表。请参见以下查询:

select a.*
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid
update a
set a.id = b.rid
-- select a.*
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid
我想用以下查询更新id:

select a.*
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid
update a
set a.id = b.rid
-- select a.*
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid
但它又回来了

主键冲突错误,因为表temp1中存在主键

我想删除该值,如果它已经存在,如果不存在,那么我想更新

比如说 id nid 1 10 2 10-要更新但无法更新此bcoz,因为它违反主键,所以删除此行。 2 11-能够更新此行,但其他两行会导致问题。 3 10-要更新但无法更新此bcoz,因为它违反主键,所以删除此行


请建议其他方法执行此操作。

因为您违反了主键约束

检查下表

select B.*
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid

id rid
2   1
2   1
3   1



select * from #temp1

id   nid
1   10
2   10
2   11
3   10
您正在使用已在temp1中的join from temp设置上述第一个表的ID

您试图更新已经在temp1中的值,其中id=2,2,3

您将把两个ID2记录更新为相同的值。你不能这样做,句号。除了放弃PK之外,没有其他方法可以解决这个问题,我认为这是个坏主意


您可能需要在pdate中进一步定义,以指定要更新的多个记录中的哪一个,或者您可能需要删除该记录,该记录可能会在更新之前成为重复记录。由于不知道您实际要完成的业务规则或您的数据意味着什么,因此无法说出您可以做些什么来解决您的问题。在这种情况下,解决方案取决于含义,当然我们在这里没有任何含义。

不要这样做-主键必须放在那里是有原因的。是的,如果该值已经存在,我想删除它如果不存在,那么我想更新,例如id nid 1 10 2 10-想更新但不能更新它违反主键,因此删除此2 11-希望更新,但问题是其他2行。3 10-想要更新但不能更新此bcoz它违反主键所以删除此是我想要删除该值如果它已经存在如果不存在那么我想要更新例如id nid 1 10 2 10-想要更新但不能更新此bcoz它违反主键所以删除此2 11-想要更新可以这样做但问题是其他2排。3 10-要更新但无法更新此bcoz,因为它违反了主键,所以请删除此bcoz