I have a function with a static output that works. (Postgres v.10) This returns the Amount of users per Server.
Here is the code:
CREATE OR REPLACE FUNCTION public.test()
RETURNS SETOF record
LANGUAGE plpgsql
AS $function$
DECLARE
var_req TEXT;
var_error text;
rec_key record;
cur_key CURSOR FOR Select s.srv,s.host,s.port from public.connections() s where s.online = true;
BEGIN
open cur_key;
loop
fetch cur_key into rec_key;
EXIT WHEN NOT FOUND;
var_req :=
'Select * from dblink(
''host=' || rec_key.host || '
port=' || rec_key.port || '
user=**
password=**
dbname=mydb'',
''
select '''''|| rec_key.srv ||''''' as srv ,count (*) as total from users '') as (srv varchar,total integer)
';
return query execute var_req;
end loop;
close cur_key;
END
$function$
;
Output =
srv total
rp1 50
sr2 41
xy 100
To be able to use reuse this query i want to move out the sql part so that i can pass it as parameter.
CREATE OR REPLACE FUNCTION public.test2(text)
RETURNS SETOF record
LANGUAGE plpgsql
AS $function$
DECLARE
var_req TEXT;
var_error text;
rec_key record;
cur_key CURSOR FOR Select s.srv,s.host,s.port from public.connections() s where s.online = true;
BEGIN
open cur_key;
loop
fetch cur_key into rec_key;
EXIT WHEN NOT FOUND;
var_req :=
'Select * from dblink(
''host=' || rec_key.host || '
port=' || rec_key.port || '
user=**
password=**
dbname=**'',
''
' || $1 || '
';
return query execute var_req;
end loop;
close cur_key;
END
$function$
;
Now when i try to make exact the same query with the dynamic function i don't get it to work. Like this i am pretty close to my goal but instead of using what's inside the rec_key.srv variable it returns '''''|| rec_key.srv ||''''' :(
select * from public.test2('select ''''''''''''|| rec_key.srv ||'''''''''''' as srv ,count (*) as total from users '') as (srv varchar,total integer)') as (srv varchar,total integer)
Output =
srv total
'''''|| rec_key.srv ||''''' 50
'''''|| rec_key.srv ||''''' 41
'''''|| rec_key.srv ||''''' 100
Can someone explain me how i can call what's inside the variable rec_key.srv with the new function?