【问题标题】:Copy partial data from one SQL DB to another将部分数据从一个 SQL DB 复制到另一个
【发布时间】:2021-07-12 09:45:18
【问题描述】:

我需要将一些数据从一个数据库中的一个表复制到另一个数据库。所以我有一个带有 table1 的 db1,其中一些列说 column1(唯一 ID)、column2column3 等。现在我有另一个 db,它是第一个的副本(模式被复制,它也会有db1) 中预先存在的一些数据。

所以db1/table1 有记录:

column1          column2                   column3
1          12/07/2021 11:60:32         10/03/2021 01:34:00
2          02/02/2021 15:30:32         11/01/2021 15:31:32
3          12/03/2021 17:20:32         13/02/2021 15:30:32
4          12/04/2021 13:40:32         16/08/2021 15:30:34
5          12/06/2021 19:10:32         17/03/2021 15:20:31

db2/table2 有以下数据:

column1          column2                   column3
1                 null                      null
2          02/03/2021 15:30:32              null
5          22/05/2021 15:30:32         12/07/2021 15:30:32
6          22/05/2021 15:30:32         12/07/2021 15:30:32
7          22/05/2021 15:30:32         12/07/2021 15:30:32

我想将数据从db1/table1 复制到db2/table2,但db2/table2 中不存在的数据除外(基于用作标识符的column1)。所以在本例中,column1 值为 3 和 4 的记录不应复制到 db2/table2 中。

如果所有记录都存在于db2/table2 中,我可以让它工作,但是当记录丢失时,它会出现错误,提示不存在记录。抱歉,如果这是一个微不足道的问题,我对 SQL 不太擅长,并试图找出一种方法来做到这一点。谢谢。

【问题讨论】:

  • 更新您的问题并显示您想要的结果。

标签: sql sql-server


【解决方案1】:

如果您想复制table2 存在的行,那么您可以使用not exists

insert into db2.table2 (col1, col2, col3)
    select t1.col1, t1.col2, t1.col3
    from db1.table1 t1
    where not exists (select 1 from db2.table2 t2 where t2.col1 = t1.col1);

以上似乎是明智的。但是,如果您想更新 table2 中的值仅用于匹配,则使用 updatejoin

update t2
    set t2.col2 = t1.col2,
        t2.col3 = t1.col3
    from table2 t2 join
         table1 t1
         on t2.col1 = t1.col1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多