【问题标题】:Equivalent for Merge with output clause in SQL Server to Postgresql等效于将 SQL Server 中的输出子句合并到 Postgresql
【发布时间】:2020-07-26 22:06:32
【问题描述】:

我想将基于以下代码的值插入到 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吗?
  • 是的,操作员甚至在评论on 1 = 2 -- Impossible Condition so they never match
  • @Andronicus:问题是:为什么?为什么这在 SQL Server 中是必需的,而不是简单的 insert into .. select from ...
  • 我正在从 SQL Server 迁移到 PostgreSQL。客户编写了这样的代码,因此我想知道如何在 PostgreSQL 中处理输出子句和插入记录

标签: sql postgresql merge common-table-expression temp-tables


【解决方案1】:

我一开始就不懂 MERGE 的用法。

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

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

【讨论】:

    猜你喜欢
    • 2015-10-07
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 2018-02-06
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多