Is there a way to use variable name dynamically, I mean compose it as a string and then use it.
Please don't tell me to use array, the example I have shown is only simplification for better picture.
do $$
declare
var1 int:=1;
var2 int:=2;
var3 int:=3;
i int;
begin
raise notice 'Variable x %' , var1;
raise notice 'Variable x %' , var2;
raise notice 'Variable x %' , var3;
for i in 1..3 loop raise
notice 'Variable x %' , 'var' || i;
end loop;
end
$$
Result
NOTICE: Variable x 1
NOTICE: Variable x 2
NOTICE: Variable x 3
NOTICE: Variable x var1
NOTICE: Variable x var2
NOTICE: Variable x var3
So I would need something like this except the result should be the numbers not the string Variable x var1 but Variable x 1
And Execute doesn't work either
do
$$
declare
var1 text = 'car';
var2 text = 'truck';
var3 text = 'boat';
code text ;
begin
for i in 1..3 loop
code = 'Insert into My_table values (' || i || ',' || 'var' || i || ');';
execute code;
end loop;
end
$$
ERROR: column "var1" does not exist
LINE 1: Insert into My_table values (1,var1);
Any ideas how to dynamically compose variable name, and as I said those examples are simple just to show my point. I need to change more than just a number in variable therefore array isn't a solution for me.
EXECUTE, but No substitution of PL/pgSQL variables is done on the computed command string. Any required variable values must be inserted in the command string as it is constructed; or you can use parameters -- so no, it cannot be done the way, you requested. In fact, using arrays won't help you either (usually, but maybe something like a hash-table / map might help you (likehstoreorjson(b))