PostgreSQL存储过程,如何返回结果集

时间:2013-10-07 08:12:40

标签: postgresql stored-procedures resultset psql sql

我尝试创建一个返回结果集的存储过程。我正在使用动态查询,因此它首先通过字符串创建,然后在过程结束时执行。我只是不知道如何返回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;

2 个答案:

答案 0 :(得分:1)

你发现,你错过了一个分号。

然而,你显然为自己制造的东西过于复杂。删除整行,然后执行:

RETURN QUERY fullsql;

应该更优雅地完成这个伎俩。通过将其转换为内联视图只是为了给它一个别名,你什么都得不到。

答案 1 :(得分:0)

我很抱歉。我能够解决这个问题。问题是这一行没有分号

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

我觉得很蠢。无论如何,为了帮助那些对存储过程有疑问,你去吧。