繁体   English   中英

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

[英]Insert into table from another table where the records don't exist

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

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)

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

先感谢您!

问题是您的内部查询无论如何都不依赖于临时表。 基本上,您写的是“如果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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM