【问题标题】:SQL Insert Into Where Record Not ExistsSQL 插入记录不存在的地方
【发布时间】:2017-04-14 23:03:59
【问题描述】:

我有一个自动化流程,每周都会将数据附加到Table1。它只有 4 列 [Reason, Number of Occurences, Sent Date, and Program]Table1 不断增长,不关心重复记录。 (每周只有 26 条记录,只有 4 列,因此性能/空间不是问题)

我有另一个表 Table2,我只想要来自 Table1 的不同记录。如果记录已经存在于Table 2 我不想插入记录。 我认为下面的语句会起作用,但它不起作用:

begin transaction
insert into [Database]..[Table2]
select Distinct * from [Database]..[Table1]
where not exists (select * from [Database]..[Table2])

(0 row(s) affected)

如果我注释掉 WHERE 子句,它会起作用,但它会插入 Table2 中已经存在的记录

begin transaction
    insert into [Database]..[Table2]
    select Distinct * from [Database]..[Table1]
    --where not exists (select * from [Database]..[Table2])

(83 row(s) affected)

如何检查 Table1 中的不同记录,如果 Table2 中不存在该记录,请插入该记录?

我正在使用 MS SQL Server 版本 11.0.6020.0

【问题讨论】:

  • IMO 如果您使用 IF 语句,那么您所做的将更具可读性。
  • 你真的需要有两个表——为什么不让 table2 成为 table1 的视图?
  • @Hogan,你知道吗...这实际上可能是一种选择。我会提出来的。

标签: sql sql-server insert-into


【解决方案1】:

在 SQL Server 中,您将使用 except。假设表具有相同的列:

insert into [Database]..[Table2]
    select Distinct t1.*
    from [Database]..[Table1] t1
    except
    select t2.*
    from [Database]..[Table2] t2;

您的not exists 子句与table1 中的数据不相关,因此它没有达到您的预期。

【讨论】:

  • 谢谢。不知道 EXCEPT 是要使用的东西。这仅仅是一个 MS SQL Server 的东西,还是你也可以在 Oracle 之类的东西中使用它?您也愿意链接任何文档吗?似乎找不到这个,因此 StackOverflow 问题。
  • @MattR 。 . .这个想法在几个数据库中得到了支持。有时它被称为MINUS
【解决方案2】:

我认为您也可以使用 MERGE 语句,它只有一个条件 WHEN NOT MATCHED BY TARGET 然后您将直接在目标表中插入该行。

注意:请考虑源表中的 DISTINCT 行。

【讨论】:

    【解决方案3】:

    您需要在内部选择中添加一个额外的 WHERE 子句来比较 table2 和 table1 记录:

    begin transaction
    insert into [Database]..[Table2]
    select Distinct * from [Database]..[Table1] t1
    where not exists (
      select * from [Database]..[Table2] t2 
      where t1.reason=t2.reason 
        AND t1.occurences=t2.occurences 
        AND t1.sent_date=t2.sent_date 
        AND t1.program=t2.program
    )
    

    【讨论】:

    • 我想过这样做,但是对于一个简单的任务来说似乎需要很多代码。
    • 如果记录的数量微不足道,并且您似乎没有保留任何技术日期(记录的创建或更新)的痕迹,您也可以 TRUNCATE 表 2,然后使用简单的 INSERT INTO table2 SELECT DISTINCT * FROM table1
    • 这是一个有效的观点,我也想到了这一点。但我团队的其他成员不喜欢这个主意。不过还是有好处的。
    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 2021-01-02
    • 2021-09-03
    • 1970-01-01
    • 2021-09-16
    相关资源
    最近更新 更多