[英]How to return a result from an anonymous PL/pgSQL block?
PostgreSQL version I'm using is 9.3. 我使用的PostgreSQL版本是9.3。
I've written a code which contains the following chunk: 我编写了包含以下代码块的代码:
String queryString = "do $$\n"
+ "<< outerblock >>\n"
+ "DECLARE\n"
+ "table_name varchar DEFAULT 'partner.partner_statistic';\n"
+ "BEGIN\n"
+ "EXECUTE 'SELECT * FROM ' || table_name;\n"
+ "END;\n"
+ "$$ LANGUAGE plpgsql; \n";
Query query = getSession().createSQLQuery(queryString);
List l = query.list();
In the debugger, I recieve the message: 在调试器中,我收到以下消息:
[org.hibernate.util.JDBCExceptionReporter.logExceptions(JDBCExceptionReporter.java:78)] : No results were returned by the query. [org.hibernate.util.JDBCExceptionReporter.logExceptions(JDBCExceptionReporter.java:78)]:查询未返回任何结果。
at the line 在行
List l = criteria.list();
How can I rewrite the query to return actual result? 如何重写查询以返回实际结果?
The solution I was looking for is that: 我一直在寻找的解决方案是:
CREATE FUNCTION res() RETURNS SETOF partner.partner_statistic AS $$
<< outerblock >>
DECLARE
r partner.partner_statistic%rowtype;
table_name varchar DEFAULT 'partner.partner_statistic';
BEGIN
FOR r IN
SELECT * FROM partner.partner_statistic offset 0 limit 100
LOOP
RETURN NEXT r;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
SELECT * FROM res();
Relevant documentation reference is here . 相关文档参考在这里 。
UPDATE: As @a_horse_with_no_name said in comment, there was more simple solution to do that: 更新:正如@a_horse_with_no_name在评论中所说,有一个更简单的解决方案可以做到这一点:
CREATE FUNCTION res() RETURNS SETOF partner.partner_statistic AS $$
<< outerblock >>
DECLARE
r partner.partner_statistic%rowtype;
table_name varchar DEFAULT 'partner.partner_statistic';
BEGIN
RETURN QUERY SELECT * FROM partner.partner_statistic offset 0 limit 100
END;
$$ LANGUAGE plpgsql;
SELECT * FROM res();
Per documentation , a DO statement can't return anything: 根据文档 ,DO语句不能返回任何内容:
The code block is treated as though it were the body of a function with no parameters, returning void 代码块被视为没有参数的函数主体, 返回void
If the code inside the DO is meant to generate rows, you may put them into a temporary table and have the client SELECT from that table. 如果DO内的代码用于生成行,则可以将它们放入临时表中,并使客户端从该表中进行SELECT。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.