PL / pgSQL函数:如何使用execute语句返回表

时间:2013-08-06 15:55:01

标签: function postgresql stored-procedures plpgsql

我有这个 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声明,但我看不出怎么办。

有什么想法吗?

3 个答案:

答案 0 :(得分:35)

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

创建表格: public.users

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

插入一些记录:

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

功能: my_function

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

答案 1 :(得分:3)

调用函数:

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setContentType("text/plain");

        System.out.println("Login request for " + username + " / " + password);
        if (username.equals("test1234")) {
            // send test response to output
            printMessageToOutputStream(resp, "OK", true, true);
        }
        else {
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN); // not working for 400,401,403
            printMessageToOutputStream(resp, "NOK", false , true);
        }
    }

不仅仅是选择。我做了,它的工作

答案 2 :(得分:0)

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

根据选择的语法,从函数接收到的输出会有差异:

select * from myfunction();

select myfunction();