1

Consider a function like that:

CREATE OR REPLACE FUNCTION public.foo(
    string1 character varying    
    )
  RETURNS integer AS
$BODY$
DECLARE
id1 INTEGER;

BEGIN

id1  := (SELECT id FROM mytable WHERE mycolumn = string1);
END;
......

It works fine and I get the id1 value for using in other part of the function.

Now, I want to rewrite the function and pass a name who act like identifier of the table.

  CREATE OR REPLACE FUNCTION public.foo(
        string1 character varying,
        tablecode character varying --new argument
        )
      RETURNS integer AS
    $BODY$
    DECLARE
    id1 INTEGER;

    BEGIN
.....

And now, there are my attepms for get id1 value and the errors:

EXECUTE FORMAT('id1 := (SELECT id FROM %I WHERE mycolumn = %s)', tablecode||'_Conceptos', quote_literal(string1));

Error:

ERROR:  syntax error at or near "id1"
LINE 1: id1 := (SELECT id FROM "CENZANO_Conceptos" WHERE codigo ...
        ^
QUERY:  id1 := (SELECT id FROM "CENZANO_Conceptos" WHERE codigo = 'CENZANO')

--second attepm

 EXECUTE FORMAT ('SELECT %I.id INTO id1 FROM %I WHERE mycolumn = %s', tablecode||'_Conceptos',tablecode||'_Conceptos',quote_literal(string1));

END;
......

Error:

ERROR:  EXECUTE of SELECT ... INTO is not implemented
HINT:  You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.

Thanks in advance

1 Answer 1

1

You could use INTO:

EXECUTE FORMAT('(SELECT id FROM %I WHERE mycolumn = %s)'
                , tablecode||'_Conceptos', quote_literal(string1)) INTO id1;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. It works fine. I have a bunch of functions where I must to add the table like argument and it's being a headache for me ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.