从不存在记录的另一个表插入表

DJD*_*J23 1 sql insert teradata insert-into sql-insert

我正在尝试找出如何从临时表(temp)插入现有表(tbl01)中的临时表(temp)中。我希望这是有道理的。我基本上是在尝试使用自表的上一次更新以来发生的记录来更新表。到目前为止,这是我的代码:

insert into tbl01
(sale_store, sale_dt, sale_register, sale_trans)
select distinct
sale_store, sale_dt, sale_register, sale_trans
from temp
where NOT EXISTS (select * from tbl01)
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是它可以运行,但不会在表中放入任何新记录 -应该有很多新记录。我确定这是我所缺少的小而愚蠢的东西。我以这篇文章为指导:如何避免在SQL Server的INSERT INTO SELECT查询中重复?

先感谢您!

Zoh*_*led 5

问题是您的内部查询无论如何都不依赖于临时表。基本上,您写的是“ tbl01如果没有记录存在,则插入tbl01”。要解决此问题,您需要在查询中添加where子句exists

insert into tbl01
(sale_store, sale_dt, sale_register, sale_trans)
select distinct
sale_store, sale_dt, sale_register, sale_trans
from temp
where NOT EXISTS (
    select * 
    from tbl01
    where temp.sale_store = tbl01.sale_store 
    and temp.sale_dt = tbl01.sale_dt
    and temp.sale_register = tbl01.sale_register
    and temp.sale_trans = tbl01.sale_trans)
Run Code Online (Sandbox Code Playgroud)