首页 > 解决方案 > 用另一个表列中的值更新和替换一个表列中的值

问题描述

我有 2 张桌子:

id | bsi | cell 

1  | 45 | NULL
2  | 23 | 600-1167
3  | 47 | 
4  | 89 | 501- -
5  | 98 | 603-5670

我想用 bsi 匹配两个表的另一个表中另一个列的数据替换单元格值

这是我的第二张桌子:

id | bsi | contact 

1  | 45 | 610-5896 
2  | 23 | 605-4567 
3  | 47 | NULL 
4  | 89 | 689-9089
5  | 98 | NULL

我希望第一个表中的每个值都替换为第二个表中的新值,以及两个表在 bsi 代码中匹配的值,即一旦第二个表中有一个值,用新值替换 NULL 和 '501- -' .

所以结果应该是一个更新的表,如下所示:

id | bsi | cell 

1  | 45 | 610-5896
2  | 23 | 605-4567
3  | 47 | NULL
4  | 89 | 689-9089
5  | 98 | 603-5670

我已经尝试过这个查询,但它只替换了新值,并且似乎为 table1 而不是 table2 中的项目写入空值。我想保留表 1 但不是表 2 中的 table1 值。

UPDATE Table1 
   SET Table1.cell = Table2.Contact
   FROM Table1  INNER JOIN Table1 ON Table1.bsi = Table2.bsi

标签: sqlsql-server

解决方案


您的加入似乎有点偏离...您没有加入第二张桌子

UPDATE t1
   SET t1.cell = t2.Contact
   FROM Table1  t1
   INNER JOIN Table2 t2 ON           --changed to table2
   t1.bsi = t2.bsi 
   --where <some condition>

此外,仅更新所有行比使用where clause. 请参阅 Aaron Bertrand 对此的测试。我这样做是因为尽管您说我想保留 table1 中的值 table 1 但不是 table 2,但这并没有反映在您的预期输出中。如果您确实想有条件地更新它们,那么您需要添加where clause.

在此处查看演示

create table table1 (id int, bsi int, cell varchar(16))

create table table2 (id int, bsi int, contact varchar(16))

insert into table1 values
(1,45,NULL),
(2,23,'600-1167'),
(3,47,''), 
(4,89,'501- -')

insert into table2 values
(1,45,'610-5896'), 
(2,23,'605-4567'), 
(3,47,NULL), 
(4,89,'689-9089')

UPDATE t1
   SET t1.cell = t2.Contact
   FROM Table1  t1
   INNER JOIN Table2 t2 ON           --changed to table2
   t1.bsi = t2.bsi 
   --where <some condition>


select * from table1

回报

+----+-----+----------+
| id | bsi |   cell   |
+----+-----+----------+
|  1 |  45 | 610-5896 |
|  2 |  23 | 605-4567 |
|  3 |  47 |          |
|  4 |  89 | 689-908  |
+----+-----+----------+

推荐阅读