【问题标题】:PostgreSQL Stored Procedure, How to Return Result SetPostgreSQL 存储过程,如何返回结果集
【发布时间】:2013-10-07 08:12:40
【问题描述】:

我试图创建一个将返回结果集的存储过程。我正在使用动态查询,因此它首先通过字符串创建,然后在过程结束时执行。我只是不知道如何返回 Select 语句的整个结果。

我的查询有效,因为我已经对其进行了测试(不要介意选择查询,它只是一个示例)。你如何正确地做到这一点?有人可以帮我解决这个问题吗?

这是我的存储过程:

  CREATE or REPLACE FUNCTION getTranscriptData(fromDate text, toDate text, idno integer = 0) 
RETURNS  TABLE(
    id integer,
    employee_id integer,
    employee_name text,
    client_id integer,
    client_name text
) AS -- text AS --
$body$
DECLARE
whereclause TEXT;
fullsql TEXT;
records RECORD;
exeQuery TEXT;

BEGIN

IF idno = 0 THEN
    whereclause := 'WHERE logs.timestamp  - INTERVAL ''12 hours''  >= ''' || fromDate || '''::timestamp ';
    whereclause := whereclause|| ' AND logs.timestamp  - INTERVAL ''12 hours'' <= ''' || toDate || '''::timestamp';
ELSE
    whereclause := ' WHERE trans.trans_id IN (1,2,3) ';
END IF;

--RAISE NOTICE 'Whereclause = "%"', whereclause;


fullsql:= 'SELECT
        trans.trans_id AS id, agent.account_id AS agent_id, agent.lastname || '', '' || agent.firstname AS agent_name, 
        client.account_id AS client_id, client.lastname || '', '' || client.firstname AS client_name
      FROM chat_transcript_archive trans
      INNER JOIN Client_session_archive csession ON csession.client_session_id = trans.client_session_id
      INNER JOIN client_queue_archive clientq ON clientq.Client_queue_id = trans.Client_queue_id
      INNER JOIN agent_session_archive asession ON asession.agent_session_id = trans.agent_session_id
      INNER JOIN agent_queue_archive agentq ON agentq.agent_queue_id = trans.agent_queue_id
      INNER JOIN accounts client ON client.account_id = csession.client_id
' || whereclause || '

      GROUP BY trans.trans_id, agent.account_id, agent.lastname, agent.firstname, client.account_id, client.lastname, client.firstname

      ORDER BY 13';

RAISE NOTICE 'FULL Query = "%"', fullsql;

exeQuery := 'SELECT * FROM (' || fullsql || ') AS records'

RETURN QUERY EXECUTE exeQuery;

END
$body$
LANGUAGE plpgsql;

【问题讨论】:

    标签: postgresql stored-procedures resultset psql sql


    【解决方案1】:

    如你所见,你漏掉了一个分号。

    但是,您显然让事情变得对自己来说太复杂了。删除整行并做:

    RETURN QUERY fullsql;
    

    应该更优雅地完成这个技巧。把它变成一个内联视图只是给它一个别名,你什么也得不到。

    【讨论】:

      【解决方案2】:

      对不起各位。我能够解决这个问题。问题是这一行没有分号

       exeQuery := 'SELECT * FROM (' || fullsql || ') AS records'
      

      我觉得自己好傻。无论如何,帮助那些对存储过程有疑问的人。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-23
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多