Sql server 如何在SQL Server/Azure SQL中比较两个表并用其他表中的值替换空值

Sql server 如何在SQL Server/Azure SQL中比较两个表并用其他表中的值替换空值,sql-server,azure-sql-database,Sql Server,Azure Sql Database,我有两个结构相同但值略有不同的表。如果表1的记录的某些列值为null,则必须更新为表2中的值,反之亦然 表1 +--------------------+ | id | exp | last | +--------------------+ | 1 | null | 4005 | | 2 | null | null | | 3 | 10/19 | 1001 | +--------------------+ 表2 +-------------------+ | id |

我有两个结构相同但值略有不同的表。如果表1的记录的某些列值为null,则必须更新为表2中的值,反之亦然

表1

+--------------------+
|  id | exp | last   |
+--------------------+
| 1  | null | 4005   |
| 2  | null | null   |
| 3  | 10/19  | 1001 |
+--------------------+
表2

+-------------------+
|  id | exp | last  |
+-------------------+
| 1  | 08/23 | null |
| 2  | 07/21 | 3867 |
| 3  | null  | 1001 |
+-------------------+
所需输出

表3

+--------------------+
|  id | code | last  |
+--------------------+
| 1  | 08/23 | 4005  |
| 2  | 07/21 | 3867  |
| 3  | 10/19  | 1001 |
+--------------------+

这是一个外部连接吗?如果是,我将如何在SQL Server/Azure SQL上执行此操作?

一个带有CASE或IIF的简单更新语句可以:

UPDATE t1 
    IIF(t1.exp IS NULL, t2.exp, t1.exp)
    IIF(t1.last IS NULL, t2.exp, t1.exp)
FROM
    Table1 t1 
LEFT JOIN Table2 t2 
    ON t1.id = t2.id 

UPDATE t2
    IIF(t2.exp IS NULL, t1.exp, t2.exp)
    IIF(t2.last IS NULL, t1.exp, t2.exp)
FROM
    Table2 t2 
LEFT JOIN Table1 t1
    ON t1.id = t2.id 
与:

如果
表1中的值不是
空值,则该值优先于
表1中的值
另外,如果两个表中的行数不相同,则应使用
左连接,从行数最多的表连接到另一个表
如果要将这些行插入到
表3

insert into table3 (id, exp, last)
select 
  t1.id,
  coalesce(t1.exp, t2.exp) exp,
  coalesce(t1.last, t2.last) last,
from table1 t1 inner join table2 t2
on t2.id = t1.id

insert into table3 (id, exp, last)
select 
  t1.id,
  coalesce(t1.exp, t2.exp) exp,
  coalesce(t1.last, t2.last) last,
from table1 t1 inner join table2 t2
on t2.id = t1.id
select t1.id,
case when t1.exp is null then concat(t1.exp, t2.exp)  when t2.exp is null then concat(t1.exp, t2.exp) 
when t1.exp is not null then (t1.exp) when t2.exp is not null then (t2.exp)  end as exp,
case when t1.last is null then concat(t1.last, t2.last) 
when t2.last is null then concat(t1.last, t2.last) when t1.last is not null then (t1.last) 
when t2.last is not null then (t2.last) end as last
from Table1 t1 join Table2 t2 on t1.id=t2.id