2

I want to use a variable as part of the statement, but it says that "tableref" doesn't exist.

CREATE OR REPLACE FUNCTION ff(tipo_acta integer, hasta date)
  RETURNS void AS
$BODY$
DECLARE 
 tableref varchar;
 r record;
BEGIN
 if tipo_acta = 1 then
          tableref = 't1';
 elsif tipo_acta = 2 then tableref = 't2';
 else tableref = 't3';
end if;

for r select id from tableref where somedate >= hasta loop
--
end loop;

I tried to use EXECUTE 'select id from ' || tableref || ' where....' but doesn't work either

I thought to get the record first with select id into r from t1 where .. and then use it in the loop, but there seems to be no way to use a record in a loop like that:

FOR r LOOP
....
END LOOP;

1 Answer 1

1

You need to use dynamic sql for that. You need to use execute command to do that in PLPG/SQL.

In your code it should be something like:

EXECUTE 'SELECT id FROM ' || tableref || ' WHERE somedate >= $1'
INTO c
USING hasta;
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I was in the right path after all FOR r IN EXECUTE ... LOOP

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.