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$$;
5
  • 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 ********** Commented Feb 13, 2016 at 19:07
  • yes same error... in fact it indicates error on "i" (in the line FOR i IN), :( Commented Feb 13, 2016 at 19:17
  • Should i be declared somewhere ? because it is like it should be declared ! Commented Feb 13, 2016 at 19:18
  • 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 Commented Feb 13, 2016 at 19:20
  • So gooood , thank you :) so the issue in the first script was "i.stmt" should be "i" instead :) Commented Feb 13, 2016 at 19:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.