0

I would like to create four databases in for-loop. However, I got an error. Could you help me to resolve this problem ?

DO $$
    BEGIN
        FOR counter IN 1..2 LOOP
            CREATE DATABASE 'database_name_%', counter;
        END LOOP;
END; $$
ERROR:  syntax error at or near "'Counter: %'"
LINE 4:             CREATE DATABASE 'Counter: %', counter;

1 Answer 1

1

From documentation for the CREATE DATABASE command:

CREATE DATABASE cannot be executed inside a transaction block.

And since:

PostgreSQL actually treats every SQL statement as being executed within a transaction. If you do not issue a BEGIN command, then each individual statement has an implicit BEGIN and (if successful) COMMIT wrapped around it. A group of statements surrounded by BEGIN and COMMIT is sometimes called a transaction block

You can't create database in functions. So even if you can handle current problem, you won't be able to execute this function.

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.