0

I have a pgscript that runs in a loop.

SET @id = 1;
BEGIN
WHILE @id <= 10

/*
CREATE TABLE tbl_name AS
SELECT * FROM main_tbl
WHERE id = @id
;

INSERT INTO tbl_name
SELECT * FROM main_tbl
WHERE id = @id
*/

SET @id = @id + 1;

END

For the first iteration id=1, I want my script to create a table because the table does not exist. For the upcoming loop id=2...3...4...so on, I want the script to insert into the table that was created.

Currently, I am creating an empty table before running the PgScript. Is there a way to write a script that creates the table for the first loop and insert in the upcoming iterations?

3
  • You should make it clear in your question that you are talking about a feature, PgScript, that is pgAdmin specific. Commented Dec 22, 2020 at 18:19
  • 2
    Why not create the table before the loop? Commented Dec 22, 2020 at 18:21
  • "Currently, I am creating an empty table before running the PgScript" - what's wrong with that? You also don't need pgScript or even a loop to do what you want. A simple insert into target_table select * from some_table where id between 1 and 10 will be much more efficient. Plus it would work with any SQL client Commented Dec 22, 2020 at 18:49

1 Answer 1

0

Try this:

CREATE TABLE IF NOT EXISTS words (
    id SERIAL PRIMARY KEY,
    word VARCHAR(500) NOT NULL
);

INSERT INTO words
        VALUES(DEFAULT, '1234');

SELECT *
FROM words;
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, my mistake. Now this example will works

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.