如何从插入查询返回PK?

时间:2016-01-12 11:46:09

标签: sql postgresql

我有一个带序列的postgresql表:

CREATE TABLE A (
  id integer NOT NULL DEFAULT nextval('a_seq'::regclass),
  X integer,
  Y integer,
  Z boolean default false,
  CONSTRAINT A_pkey PRIMARY KEY (id)
)

我在函数中有一个插入语句如下:

insert into A(x,y) select $1,getdig();

我希望此插入返回id行被赋予名为A_id的函数varabile

应该是这样的:

CREATE OR REPLACE FUNCTION bbb(m integer)
  RETURNS integer AS
$BODY$
declare 
     A_id  int;
begin
    insert into A(x,y) select $1,getdig() RETURNING id into A_id;

     actions using  A_id like:
     update A set z=True where id=A_id;

end;
$BODY$
  LANGUAGE plpgsql VOLATILE

我该怎么做?

2 个答案:

答案 0 :(得分:2)

不需要select

CREATE OR REPLACE FUNCTION bbb(m integer)
  RETURNS integer AS
$BODY$
declare 
     A_id  int;
begin
    insert into A(x,y) 
    values ($1,getdig()) 
    RETURNING id into A_id;

    -- actions using  A_id like:
    update A set z=True where id=A_id;

    return a_id; -- don't forget to return something!
end;
$BODY$
  LANGUAGE plpgsql VOLATILE

答案 1 :(得分:0)

您使用return子句:

with i as (
      insert into A(x,y)
          select $1, getdig()
          returning id
     )
select *
from i;

从技术上讲,CTE不是必需的。但我更喜欢返回值的查询以SELECT开头。

相关问题