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