如何编写在PostgreSQL中返回表的非参数化函数

时间:2019-02-22 12:38:14

标签: postgresql

create or replace function demowhile_()
    returns table (id integer,name varchar(50))
        language 'plpgsql'
       as $$

    declare id integer;
    declare name varchar(50);

    begin
    CREATE temporary TABLE demo_(id integer,name varchar(50));
    CREATE temporary TABLE temp_ (id integer);
        insert into temp_ (select id from demo);

            while (select count(*) from temp_) <> 0
            loop
                id = (select top(1) id from temp_);
                name = (select name from demo where id = id);
                insert into demo_ values (id,name);

                delete from temp_ where id = id;

                end loop;

                return query select id,name from demo;
                end;
                $$;

****执行时会出现类似****

的错误
select * from demowhile();

**ERROR:  column reference "id" is ambiguous
LINE 1: insert into temp_ (select id,name from demo)
                                  ^
DETAIL:  It could refer to either a PL/pgSQL variable or a table column.
QUERY:  insert into temp_ (select id,name from demo)
CONTEXT:  PL/pgSQL function demowhile() line 9 at SQL statement
SQL state: 42702**

1 个答案:

答案 0 :(得分:1)

demowhile_() returns table (id integer,name varchar(50)demowhile_(out id integer, out name varchar(50)) returns setof record

基本相同

可以直接从函数内部引用id输出列。然后,您还创建了一个名为id的函数变量。因此,当您将值分配给id时,是分配给输出参数还是声明的变量? PG不知道,所以您会收到该错误。

当然,简单的解决方案是为每个名称赋予唯一的名称。