在Postgres中输出等效的Inserted.id

时间:2020-08-04 15:14:17

标签: postgresql

我是PostgreSQL的新手,正在尝试将mssql脚本转换为Postgres。

对于Merge语句,我们可以在冲突更新时使用insert,或者只使用下面的语句,而不能执行任何操作,

MSSQL代码:

Declare @tab2(New_Id int not null, Old_Id int not null)

MERGE Tab1 as Target
USING (select * from Tab1
        WHERE ColumnId = @ID) as Source on 0 = 1
        when not matched by Target then
    INSERT 
       (ColumnId
       ,Col1
       ,Col2
       ,Col3
      )
 VALUES (Source.ColumnId
       ,Source.Col1
       ,Source.Col2
       ,Source.Col3
       )
OUTPUT INSERTED.Id, Source.Id into @tab2(New_Id, Old_Id);

Postgres代码:

Create temp table tab2(New_Id int not null, Old_Id int not null)

With source as( select * from Tab1
        WHERE ColumnId = ID)
Insert into Tab1(ColumnId
       ,Col1
       ,Col2
       ,Col3
       )
select Source.ColumnId
        ,Source.Col1
       ,Source.Col2
       ,Source.Col3
       from source

我的查询是如何在postgres中转换OUTPUT INSERTED.Id。我需要此ID才能在另一个表中插入记录(可以说是基于Tab1中的Inserted值作为子表)

1 个答案:

答案 0 :(得分:1)

在PostgreSQL的INSERT语句中,您可以选择查询应返回的内容。来自docs on INSERT

可选的RETURNING子句使INSERT根据实际插入(或使用ON CONFLICT DO UPDATE子句进行更新)的每一行计算并返回值。这对于获取默认提供的值(例如序列号)很有用。但是,允许使用表列的任何表达式。 RETURNING列表的语法与SELECT的输出列表的语法相同。仅返回成功插入或更新的行。

示例(查询的缩写形式):

WITH [...] INSERT INTO Tab1 ([...]) SELECT [...] FROM [...] RETURNING Tab1.id