【发布时间】: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