0

I have a table with schema names. I am writing a procedure to select schema name from the table and into a variable. The variable is then used to fetch records from the schema table. Sample code below.

CREATE OR REPLACE PROCEDURE vasmol_master.sp_pushmt(
    )
LANGUAGE 'plpgsql'
AS $BODY$

DECLARE
    shortcodedatabase CHARACTER VARYING;
    services CHARACTER VARYING;
    BEGIN
         FOR shortcodedatabase IN SELECT dbase FROM vasmol_master.shortcode_services ORDER BY shortcode ASC LOOP
            services := shortcodedatabase ||'.smsservices';
            
            SELECT * FROM services;
        END LOOP;
    END

$BODY$;
2
  • See the manuals. postgresql.org/docs/current/… Commented Mar 1, 2022 at 10:54
  • From the answer I might have an idea what the question is, but I don't know what the problem is. Can you please add detail for both of these? Commented May 25, 2022 at 19:01

1 Answer 1

4

As the documentation linked to in a comment by Richard Huxton explains, to substitute a variable identifier into a query, use EXECUTE. See the documentation.

Depending on the return values you want, your procedure could look something like the following. This uses format to create a query string, substituting in the schema name as an identifier (%I).

CREATE OR REPLACE PROCEDURE vasmol_master.sp_pushmt()
  LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
  shortcodedatabase CHARACTER VARYING;
BEGIN
  FOR shortcodedatabase IN
    SELECT dbase
    FROM vasmol_master.shortcode_services
    ORDER BY shortcode ASC
  LOOP
    EXECUTE format('SELECT * FROM %I.smsservices', shortcodedatabase);
  END LOOP;
END
$BODY$;
Sign up to request clarification or add additional context in comments.

Comments

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.