我试图编写一个存储过程,在其中我将查询传递到一个存储过程,该存储过程将在内部调用row_to_json函数。我们有多个DBMS(Oracle、SQL Server和postgres),希望编写一个通用过程,作为json处理函数的包装器。
我在看这样的东西

CREATE OR REPLACE FUNCTION proj.sql_row_to_json(sql_t text)
 RETURNS json
 LANGUAGE sql
AS $function$
  with t as (select sql_t )
  select row_to_json(t) from t;
$function$

我将在应用程序中调用函数
select SQL_ROW_TO_JSON('<sql query>')->应该在不同的数据库中工作
但是上面的过程给了我下面的结果,而不是实际的数据。
select SQL_ROW_TO_JSON('SELECT id,name FROM emp')

{"sql_t":"SELECT id,name FROM emp"}

最佳答案

你必须使用plpgsql和dynamic sql

create or replace function sql_row_to_json(sql_t text)
returns json language plpgsql as $function$
declare rslt json;
begin
    execute
        format($ex$
            select json_agg(row_to_json(t))
            from (%s) t
        $ex$, sql_t)
    into rslt;
    return rslt;
end;
$function$;

select sql_row_to_json('select 1 as id, ''abcd'' as value');

     sql_row_to_json
-------------------------
 {"id":1,"value":"abcd"}
(1 row)

注意,函数容易SQL-injection attacks

关于sql - 将查询传递给postgres中存储过程中的row_to_json函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43557703/

10-11 09:29
查看更多