1

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

2 回答 2

1

正如你所发现的,你错过了一个分号。

但是,您显然使事情对自己来说太复杂了。删除整条线,然后做:

RETURN QUERY fullsql;

应该更优雅地做到这一点。将它变成内联视图只是为了给它一个别名,你什么也得不到。

于 2016-06-05T06:05:25.947 回答
0

对不起,伙计们。我能够解决这个问题。问题是这一行没有分号

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

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

于 2013-10-07T08:43:00.317 回答