0

I need to drop tables (multiple tables) from the database (Postgres) which has suffix 'alpha'. There are almost 500 tables present in the database which has different suffixes and I am willing to drop tables only with the suffix 'alpha'.

Table Name Example: inventory_20170312_alpha

Abhijit
  • 491
  • 2
  • 6
  • 14

2 Answers2

1

You could use:

SELECT format('DROP TABLE IF EXISTS %s;' ,
              (SELECT string_agg(table_name, ',') 
               FROM INFORMATION_SCHEMA.TABLES  WHERE table_name LIKE '%alpha'));

Warning! I've assumed there is no FK to other tables.

DBFiddle Demo

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
0

You can try this code below. If you are working on a real product or something like that, please run it on a test environment first. Also make sure your userid has the permission of dropping a table in the database.

DECLARE @cmd varchar(4000)
DECLARE cmds CURSOR FOR
SELECT 'drop table [' + Table_Name + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Name LIKE '%alpha'

OPEN cmds
WHILE 1 = 1
BEGIN
    FETCH cmds INTO @cmd
    IF @@fetch_status != 0 BREAK
    EXEC(@cmd)
END
CLOSE cmds;
DEALLOCATE cmds
Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82