当行都不存在时,有没有更好的方法将一个表中的行插入到另一个表中?

-- Insert all the rows from the temp table into the perm table
-- if none of the rows in the temp table exist in the perm table

-- Insert none of the rows from the temp table into the perm table
-- if any of the rows in the temp table exist in the perm table

insert perm_table (key_field_a, key_field_b, attrib_c, attrib_d, attrib_e)
    select key_field_a, key_field_b, attrib_c, attrib_d, attrib_e from #temp_table
where not exists 
(
    select *
    from #temp_table temp
    join perm_table perm
        on perm.key_field_a = temp.key_field_a
        and perm.key_field_b = temp.key_field_b
)

推荐答案

您可以在条件perm.key_field_a is null为空的情况下使用left join插入TEMP_TABLE上存在但perm_table上不存在的记录:

insert perm_table (key_field_a, key_field_b, attrib_c, attrib_d, attrib_e)
select temp.key_field_a, temp.key_field_b, temp.attrib_c, temp.attrib_d, temp.attrib_e 
from #temp_table as temp
left join perm_table perm
     on perm.key_field_a = temp.key_field_a
     and perm.key_field_b = temp.key_field_b
where perm.key_field_a is null

Sql相关问答推荐

Oracle SQL对列进行汇总并在列表底部显示总计

SQL—如何根据2列填写缺失的值

Stack Exchange站点上的最短帖子(按正文长度计算,用户名为原始发帖(SEDE))

R中对Arrow duckdb工作流的SQL查询

连接特定行号

从自定义日期和时间开始,每月具有给定状态的公司数量

你能过滤一个列表只返回多个结果吗?

MS Access问题查询中的自定义字段

在VB.NET中如何在MS Access数据库中创建SQL项目历史库存卡

如何将insert语句重复n次使一个值递增?

SQL仅返回第一个字母在A-Z之间的值

替换SQL Server XML中多处出现的 node 值

删除对 JSON 数据的未解析引用的 SQL71502 警告

如何根据创建日期查找两个表中最接近的记录?

在 SQL Server 中查找重复项

在 postgresql 中保存带有时间戳的几何类型数据

BigQuery Pivot 遗漏行

SQL Server 查找存在于所有不同时期(或序列)中的条目

基于源表的 SQL INSERT、UPDATE 和 DELETE

如何使用 pg-promise 创建要在复杂的 sql 查询中使用的 VALUES 列表?