我试图创建一个将返回结果集的存储过程。我正在使用动态查询,因此它首先通过字符串创建,然后在过程结束时执行。我只是不知道如何返回 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;
当你发现时,你错过了一个分号。
然而,你显然把事情弄得对你自己来说太复杂了。 删除整行并执行:
RETURN QUERY fullsql;
应该更优雅地做这个技巧。 通过将其转换为内联视图只是为了给它一个别名,您将一无所获。
对
不起伙计们。我能够解决这个问题。问题是这一行没有分号
exeQuery := 'SELECT * FROM (' || fullsql || ') AS records'
我觉得自己太愚蠢了。无论如何,为了帮助那些对存储过程有疑问的人,你可以去吧。