1

I am trying to switch the schema name dynamically to do some data manipulation.

I am running the following.

DO $$
DECLARE schema_name TEXT;
BEGIN
FOR schema_name in
 select "name" from public.tenants
 Loop
 RAISE NOTICE 'The current schema is %', schema_name;
 INSERT INTO schema_name.campuses (select * from public.campuses where code = schema_name);
 End Loop;
END $$;

However I am presented with the following

NOTICE: The current schema is NTU

ERROR: relation "schema_name.campuses" does not exist LINE 1: INSERT INTO schema_name.campuses (select * from public.campu... ^ QUERY: INSERT INTO schema_name.campuses (select * from public.campuses where code = schema_name) CONTEXT: PL/pgSQL function inline_code_block line 8 at SQL statement SQL state: 42P01

I have tried wrapping the schema_name in "" as well as []. Is there a solution to this as my googling is not helping me at present.

asked Mar 5, 2021 at 10:35

1 Answer 1

1

This happens when you raise a WARNING try a INFO instead

Additional you need dynamic sql see https://www.postgresql.org/docs/13/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

DO $$
DECLARE schema_name TEXT;
BEGIN
SET client_min_messages TO INFO;
FOR schema_name in
 select "name" from test.public.tenants
 Loop 
 RAISE info 'The current schema is %', schema_name;
 EXECUTE CONCAT('INSERT INTO ', schema_name , '.campuses (select * from public.campuses where code = 1ドル);')
 USING schema_name;
 End Loop;
END $$;
answered Mar 5, 2021 at 12:55
2
  • Thanks for the response @nbk still getting the following error ERROR: relation "schema_name.campuses" does not exist LINE 1: INSERT INTO schema_name.campuses (select * from public.campu... Commented Mar 5, 2021 at 13:02
  • I changed my answer, to a prepared statenst Commented Mar 5, 2021 at 13:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.