Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

329
Views
pass a query to row_to_json function inside a store procedure in postgres

I am trying to write a store procedure where I pass a query into a stored procedure which will internally call the row_to_json function. We have multiple DBMS (Oracle, SQL Server & postgres) and want to write a generic procedure which will act as a wrapper for the json handling function.

I am looking at something like this

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$

I would call function in my application as

select SQL_ROW_TO_JSON('<sql query>') -> which should work across different databases

But the above procedure gives me the below result instead of the actual data.

select SQL_ROW_TO_JSON('SELECT id,name FROM emp')

{"sql_t":"SELECT id,name FROM emp"}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You have to use plpgsql and 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) 

Note that the function is prone to SQL-injection attacks.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!