如何在程序中使用临时表,Postgresql

时间:2017-11-21 16:07:00

标签: sql postgresql plpgsql

我有一张临时表

   CREATE TEMPORARY TABLE temp_location
   (
      city VARCHAR(30),
      street VARCHAR(30)
   ) 
   ON COMMIT DELETE ROWS;

我想在我的程序中使用这个表

CREATE OR REPLACE FUNCTION fexample(
    pcity character varying)
  RETURNS void AS
$BODY$
DECLARE 
BEGIN

    select * from temp_location where city = pcity;
end;
$BODY$
  LANGUAGE plpgsql VOLATILE SECURITY DEFINER
  COST 100;

此方法在oracle中工作,但不在postgresql中工作

2 个答案:

答案 0 :(得分:2)

您可以使用:

CREATE OR REPLACE FUNCTION fexample(pcity VARCHAR(30))
  RETURNS TABLE(c VARCHAR(30),a VARCHAR(30)) AS
$$
    select * from temp_location where city = pcity;
$$
  LANGUAGE sql;

<强> DBFiddle Demo

答案 1 :(得分:0)

除非我错过了船,否则我想你想要这样的东西:

CREATE OR REPLACE FUNCTION fexample(pcity character varying)
  RETURNS void AS
$BODY$
DECLARE
  rw temp_location%rowtype;
BEGIN

    for rw in select * from temp_location where city = pcity
    loop
       -- do stuff with rw
    next rw;

end;
$BODY$
  LANGUAGE plpgsql VOLATILE SECURITY DEFINER
  COST 100;

如果将rowtype声明为变量,则可以在查询中使用它。