我有這個PL/pgSQL函數,它必須返回一些用戶的信息。PL/pgSQL函數:如何用執行語句返回表
CREATE OR REPLACE FUNCTION my_function(user_id integer)
RETURNS TABLE(id integer, firstname character varying
, lastname character varying) AS
$$
DECLARE
ids character varying;
BEGIN
ids := '';
--Some code which build the ids string, not interesting for this issue
RETURN QUERY EXECUTE 'SELECT users.id, users.firstname, users.lastname
FROM public.users WHERE ids IN (' || ids || ')';
END;
$$ LANGUAGE plpgsql;
我現在面臨的問題是,該函數的結果是一個列的表是這樣的:
╔═══╦═════════════════════╗
║ ║my_function ║
╠═══╬═════════════════════╣
║ 1 ║ (106,Ned,STARK) ║
║ 2 ║ (130,Rob,STARK) ║
╚═══╩═════════════════════╝
雖然我預計:
╔═══╦════════════╦════════════╦═════════════╗
║ ║ id ║ firstname ║ lastname ║
╠═══╬════════════╬════════════╬═════════════╣
║ 1 ║ 106 ║ Ned ║ STARK ║
║ 2 ║ 103 ║ Rob ║ STARK ║
╚═══╩════════════╩════════════╩═════════════╝
我認爲(但不知道)問題來自EXECUTE
聲明,但我看不到如何做。
任何想法?
你是用'SELECT my_function(123);'還是'SELECT FROM my_function(123)'調用函數? –
你是完全正確的,我用SELECT my_function(123)執行函數;它完美地與FROM ...一起工作,謝謝! – Getz