如何在外部查询或cte中查询存储过程中创建的行

时间:2014-10-16 22:12:56

标签: postgresql

我正在尝试检索由存储过程插入的行,但该行在下一个查询之前不可用。我正在尝试做的一个简单示例如下:

create table testsp(
  id serial primary key,
  name text
);
CREATE OR REPLACE FUNCTION save(_id int DEFAULT null, _name text DEFAULT 'hi') returns int as $$
DECLARE
  _out int;
BEGIN
  INSERT INTO testsp(name) values(_name) returning id into _out;
  RETURN _out;
END;
$$ LANGUAGE PLPGSQL;

-- calling save will return the id of the inserted row
select save(_name:='foo');
 save 
------
    1
(1 row)

-- but using in an outer query, the row is not visible but was inserted
with savecte AS(select save(_name:='foo') as id) select * from testsp join savecte on testsp.id=savecte.id;
 id | name | id 
----+------+----
(0 rows)

-- same result using subquery
select * from testsp where id in(select save(_name:='foo'));)
 id | name 
----+------
(0 rows)    

0 个答案:

没有答案