Home > database >  add parameter to dynamic EXECUTE in postgreSQL
add parameter to dynamic EXECUTE in postgreSQL

Time:10-27

I have a procedure which contain this piece of code

SELECT query INTO query FROM temp_table_test WHERE id = whateverId;

EXECUTE query;

My query variable will contain something like

CALL Someprocedure (withSomeParameters)

How can i make the parameter dynamic in the first proc as they can change time to time and i can't make them static in the variable ?

in t-SQL there is something with

sp_executesql

But as I'm very new to postgres I don't know where to start.

CodePudding user response:

assuming you are using pl/pgsql, you can pass parameters with the USING clause;

EXECUTE query USING $1, $2, $3, ...;

for example;

query = 'SELECT SUM( "field_a" ) FROM "table" WHERE "field_b" = $1 AND "field_c" = $2';
EXECUTE query USING 5, 10;

this will be equal to:

SELECT SUM( "field_a" ) FROM "table" WHERE "field_b" = 5 AND "field_c" = 10;
  • Related