문제

I'm trying to convert a dynamic query result into json and then return that json as the result of this function (this is a simplified version, the WHERE clause in my actual code is considerably longer).

CREATE OR REPLACE FUNCTION get_data_as_json(tbl regclass, p_version_id integer)
  RETURNS json AS $$
BEGIN
    RETURN to_json( EXECUTE 'SELECT * FROM '|| tbl
                         || ' WHERE version_id = p_budget_version_id' );
END;
$$ LANGUAGE plpgsql;

However, this code results in a type "execute" does not exist error.
How do I run the dynamic query, and then convert the result to JSON?

올바른 솔루션이 없습니다

다른 팁

If you were returning SETOF you'd need to use the RETURN QUERY EXECUTE construct, producing a dynamic query that returns what you want. Since you're not, use regular EXECUTE ... INTO a variable that you then return.

Untested, but in vaguely the right direction:

CREATE OR REPLACE FUNCTION get_data_as_json(tbl regclass, p_version_id integer) RETURNS json AS $$
DECLARE
    my_result json;
BEGIN
    EXECUTE format('SELECT to_json(*) FROM %I WHERE version_id = p_budget_version_id',tbl) INTO my_result;
    RETURN my_result;
END;
$$ LANGUAGE plpgsql;

What @Craig wrote. But a somewhat different solution with additional fixes:

CREATE OR REPLACE FUNCTION get_data_as_json(tbl regclass
                                          , p_version_id integer
                                          , OUT my_result json) AS
$func$
BEGIN
   EXECUTE format('SELECT to_json(*) FROM %s
                   WHERE  version_id = $1'
                  ,tbl)
   INTO  my_result
   USING p_version_id;
END
$func$ LANGUAGE plpgsql;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top