用于将数据插入不存在的表中的 Oracle 代码



我正在尝试将数据插入到Oracle数据库中的表中。数据已经存在,但不是所有数据,我不能只是删除数据并重新插入所有数据。有没有办法将数据插入表中(不知道我缺少什么数据)。我的脚本正在运行,但实际上没有插入任何数据(而且我知道缺少数据。我故意将数据取出以测试其重新插入。

Insert into item (item, descr) 
select distinct a.SUBORD, a.SUBORD_DESCR FROM EXIDE.UDT_BOM a, item b 
where b.item = a.subord and not exists 
(select b.item from item b, exide.udt_bom a where a.subord = b.ITEM)

如果我遵循您正在做的事情,您可以使用 merge 语句:

merge into item i
using (select subord, subord_descr from exide.udt_bom) u
on (i.item = u.subord)
when not matched then insert (item, descr) values (u.subord, u.subord_descr);

SQL小提琴演示。

这样做还有一个优点,如果udt_bom对现有项目有新的描述,您也可以更新item表中的描述:

merge into item i
using (select subord, subord_descr from exide.udt_bom) u
on (i.item = u.subord)
when matched then update set descr = u.subord_descr
when not matched then insert (item, descr) values (u.subord, u.subord_descr);

另一个小提琴。

您对太多表的引用太多。 使用 not exists 子句,查询不需要显式连接:

Insert into item(item, descr) 
    select distinct b.SUBORD, b.SUBORD_DESCR
    FROM EXIDE.UDT_BOM b
    where not exists (select i.item from item i where b.subord = i.ITEM);

如果没有重复项,在udt_bom,我也会摆脱distinct。 而且,当您使用表缩写作为别名而不是无意义的字母(如 ab 等)时,查询更具可读性。

最新更新