41

我有这个PL/pgSQL函数,它必须返回一些用户信息。

CREATE OR REPLACE FUNCTION my_function(
        user_id integer
    ) RETURNS TABLE(
            id integer, 
            firstname character varying,
            lastname  character varying
        ) AS $$
    DECLARE
        ids character varying;
    BEGIN
        ids := '';
        --Some code which build the ids string, not interesting for this issue
        RETURN QUERY 
            EXECUTE 'SELECT 
                        users.id, 
                        users.firstname, 
                        users.lastname
                    FROM public.users 
                    WHERE ids IN (' || ids || ')';
    END;
$$ LANGUAGE plpgsql;

我面临的问题是函数的结果是一个像这样的单列表:

╔═══╦═════════════════════╗
║   ║my_function          ║
╠═══╬═════════════════════╣
║ 1 ║ (106,Ned,STARK)     ║
║ 2 ║ (130,Rob,STARK)     ║
╚═══╩═════════════════════╝

虽然我期望:

╔═══╦════════════╦════════════╦═════════════╗
║   ║ id         ║ firstname  ║ lastname    ║
╠═══╬════════════╬════════════╬═════════════╣
║ 1 ║ 106        ║ Ned        ║ STARK       ║
║ 2 ║ 103        ║ Rob        ║ STARK       ║
╚═══╩════════════╩════════════╩═════════════╝

我认为(但不确定)问题来自EXECUTE声明,但我不知道该怎么做。

有任何想法吗?

4

3 回答 3

55

你是如何执行该功能的?它用作选择语句。

创建表:public.users

create table public.users (id int, firstname varchar, lastname varchar);

插入一些记录:

insert into public.users values (1, 'aaa','bbb'),(2,'ccc','ddd');

功能:我的功能

CREATE OR REPLACE FUNCTION my_function(user_id integer) RETURNS TABLE(id integer, firstname character varying, lastname character varying) AS $$
    DECLARE
        ids INTEGER[];
    BEGIN
         ids := ARRAY[1,2];
         RETURN QUERY
             SELECT users.id, users.firstname, users.lastname
             FROM public.users
             WHERE users.id = ANY(ids);
    END;
$$ LANGUAGE plpgsql;

现在您可以使用 *

select * from my_function(1);

查询结果

 id | firstname | lastname 
----+-----------+----------
  1 | aaa       | bbb
  2 | ccc       | ddd

或者也有列名

select id,firstname,lastname from my_function(1);

结果

 id | firstname | lastname 
----+-----------+----------
  1 | aaa       | bbb
  2 | ccc       | ddd
于 2013-08-06T16:25:36.353 回答
12

像这样调用函数:

select * from  my_function(123);

不只是选择。我做到了,它有效

于 2017-04-20T05:49:50.033 回答
3

http://www.postgresqltutorial.com/plpgsql-function-returns-a-table/

根据选择的语法,从函数接收到的输出有所不同:

select * from myfunction();

select myfunction();
于 2018-10-02T14:25:00.793 回答