【问题标题】:How do I only import unique records into a table from another table?如何仅将唯一记录从另一个表导入到一个表中?
【发布时间】:2022-01-19 23:16:57
【问题描述】:

我正在尝试更新 SQL Server 中的表。表称为 table1 列(代码,描述)。我想用 table2(code, desc) 中的唯一记录更新 table1。 table2 是 table1 的副本,但它包含 table1 中不存在的记录。

编辑 1:table1 包含 7 月份导出时我们 ERP 中的所有记录,table2 包含 11 月份导出时我们 ERP 中的所有记录(包括 7 月之后添加的记录,这些记录是我要添加到 table1 的记录)

【问题讨论】:

  • 您似乎只想要一个UPDATE 和一个JOIN,不是吗?

标签: sql sql-server


【解决方案1】:

听起来你想要INSERT

这样的事情应该可以工作:

INSERT INTO table1 (code, desc)
SELECT t2.code, t2.desc
FROM table2 t2
LEFT JOIN table1 t1 on t2.code = t1.code and t1.desc = t2.desc
WHERE t1.code is null --Ignore records that already exist in table1

... 相应地调整连接子句。

【讨论】:

    【解决方案2】:

    要使用来自table2 中匹配行的值更新table1.desc,只需执行以下操作:

    update t1 set 
      t1.desc = t2.desc
    from table1 t1
    join table2 t2 on t2.code = t1.code;
    

    但是,如果您想将仅存在于 table2 中的行插入到 table1 中(如果是这种情况还不清楚),您可以使用 not exists

    insert into table1 (code, desc)
    select code, desc
    from table2 t2
    where not exists (select * from table1 t1 where t1.code = t2.code);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多