2

I want to create a script that detect and drop the public tables in my posgresql database...

The request I build is the following :

SELECT CONCAT('DROP TABLE ', table_schema,'.',table_name,';') AS stmt FROM information_schema.TABLES
WHERE table_schema='public' AND table_catalog='capsana'

Here is a screenshot of the output I got

enter image description here

I want now to execute the commands (in the stmt column) in an automatic way .. without doing copy paste !

Is there any way to do that ?

1 Answer 1

2

You can use dynamic sql to do this;

DO $$
DECLARE
    drop_stmt text;
BEGIN
    FOR drop_stmt IN 
    SELECT CONCAT('DROP TABLE ', table_schema,'.',table_name) AS stmt 
    FROM information_schema.TABLES
    WHERE table_schema='public' AND table_catalog='capsana' LOOP
        EXECUTE drop_stmt;
    END LOOP;
END$$;
Sign up to request clarification or add additional context in comments.

5 Comments

when I execute this command it says : ERROR: loop variable of loop over rows must be a record or row variable or list of scalar variables LINE 8: FOR i IN ^ ********** Erreur **********
yes same error... in fact it indicates error on "i" (in the line FOR i IN), :(
Should i be declared somewhere ? because it is like it should be declared !
Oh yes, I added : DECLARE i text; and it passes .. however it do not execute i.stmt ... it says : ERROR: missing FROM-clause entry for table "i" LINE 1: SELECT i.stmt
So gooood , thank you :) so the issue in the first script was "i.stmt" should be "i" instead :)

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.