如何更新每条记录的PK

时间:2014-06-06 18:14:12

标签: sql sql-server sql-server-2008 tsql

我有两个完全相同的表,除了一列。两个表具有相同数量的记录和相同数量的列,并且所有数据都相同。

Table A:
+--------------------------------------+--------+--------+---------+
|                 GUID                 | Animal | Person | Vehicle |
+--------------------------------------+--------+--------+---------+
| 1D001609-7071-4DBB-9E65-0000B3EEF751 | cat    | matt   | car     |
| 90260783-E3C3-4A9B-BEA0-000388EA41E1 | dog    | rich   | truck   |
| DD18FCFA-99BD-4FBC-AFC2-00058EF95D0A | zebra  | alex   | van     |
+--------------------------------------+--------+--------+---------+



Table B:
+--------------------------------------+--------+--------+---------+
|                 GUID                 | Animal | Person | Vehicle |
+--------------------------------------+--------+--------+---------+
| F67A3079-8589-4304-AA3C-000688696BAA | cat    | matt   | car     |
| C71710EC-492F-424E-805D-00068AFE4E82 | dog    | rich   | truck   |
| 5F830142-F4CC-4580-974D-000710F1AB5F | zebra  | alex   | van     |
+--------------------------------------+--------+--------+---------+

我需要将表A的GUID更新为等于表B的GUID。这样的东西会起作用:

update a
set a.guid=b.guid
from tablea a
join tableb b
on a.animal=b.animal
and a.person=b.person
and a.vehicle=b.vehicle

但上述解决方案对我不起作用。我实际上有大约50列和大约100万条记录。

关于如何更有效地更新表A中的GUID,您还有其他建议吗?

2 个答案:

答案 0 :(得分:3)

UPDATE A
SET [GUID] = (
  SELECT [GUID] 
  FROM B
  WHERE EXISTS (
    SELECT A.Animal,A.Person,A.Vehicle
    INTERSECT
    SELECT B.Animal,B.Person,B.Vehicle
  )
)

答案 1 :(得分:1)

如果你想让表格相同,那么:

DROP TABLE B

SELECT *
INTO B
FROM A