【问题标题】:Update table gives primary key violation error更新表给出主键冲突错误
【发布时间】:2014-11-21 18:31:16
【问题描述】:

我有以下拖车表

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

返回:

id  nid
2   10
2   11
3   10

我想用以下查询更新 id:

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 中的主键导致主键冲突错误。

如果该值已经存在,我想删除它,否则我想更新

例如 身份证 1 10 2 10-- 想要更新但不能更新,因为它违反了主键,所以删除这一行。 2 11 - 能够更新此行,但其他 2 行会导致问题。 3 10-- 想要更新但不能更新,因为它违反了主键,所以删除这一行。

请建议其他方法。

【问题讨论】:

  • 别这样——主键放在那里一定是有原因的。

标签: sql-server database join


【解决方案1】:

因为你违反了Primary Key Constraints

检查下表

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

您正在使用来自 #temp 的连接设置上面第一个表的 ID,该连接已经在 #temp1 中

您正在尝试更新已在 #temp1 where id=2,2,3 中的值

【讨论】:

  • 是的,如果该值已经存在,我想删除它,如果不存在,那么我想更新例如 id nid 1 10 2 10-- 想要更新但不能这样做,因为它违反了主键所以删除这 2 11 - 想要更新能够做到这一点,但问题是其他 2 行。 3 10-- 想要更新但无法更新,因为它违反了主键,所以删除它
【解决方案2】:
select *
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid 

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

您可能需要在 pdate 中进一步定义以指定要更新的多条记录中的哪一条,或者您可能需要在更新之前删除可能最终成为重复记录的记录。不了解您实际尝试完成的业务规则或您的数据意味着什么,就不可能说出您可以做些什么来解决您的问题。这种情况下,解决方案取决于含义,当然我们在这里没有含义。

【讨论】:

  • 是的,如果该值已经存在,我想删除它,如果不存在,那么我想更新例如 id nid 1 10 2 10--想要更新但不能这样做,因为它违反了主键所以删除这 2 11 - 想要更新能够做到这一点,但问题是其他 2 行。 3 10-- 想要更新但无法更新,因为它违反了主键,所以删除它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2017-07-31
相关资源
最近更新 更多