SQL Server 中带有 output 子句的合并操作在 PostgreSQL 中的等价实现方法是什么?

3
我想根据以下代码向PostgreSQL的临时表中插入值。
declare @output table (AuditScratchID bigint, AuditID bigint);

merge table atb
 using (select 
            s.ID
            ....
            ....
            ....
        from @temporaryTableVariable s
            inner join ....
...............
..............

        ) as s
 on 1 = 2 -- Impossible Condition so they never match
 when not matched then
    insert (.....)
    values (.....)
    output s.ID, inserted.ID
    into @output;

仅仅提一下,我如何将值关联到临时表中


如果你强制让MERGE永远不匹配,我不明白它应该做什么?最终这不就是一个简单的“insert into ... select from temp_table”吗? - user330315
这是,OP甚至在评论中声明了on 1 = 2 - 不可能的条件,因此它们永远不会匹配 - Andronicus
@Andronicus:问题是:为什么?在 SQL Server 中,这为什么是必要的,而不是简单地使用“insert into .. select from ...”? - user330315
我正在从SQL Server迁移到PostgreSQL。客户已经编写了这样的代码,因此我想知道如何处理输出子句并在PostgreSQL中插入记录。 - swapnil solanki
目的是建立一个匹配/映射/关系表,其中包含源ID和插入的新ID。可能的用途是保留数据移动的历史记录,以便能够回溯,或者对时间内的移动进行分析。从ScratchAudit到Audit,解决方案可以是在目标表中插入原始源ID键。 - jjdesign
1个回答

4

我一开始就不理解MERGE的用法。

这似乎是一个简单的insert ... select。要查看插入的行,请使用returning子句。

insert into atb (...)
select ... columns ...
from some_table
  join other_table on ...
returning *

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接