How to drop many (but not all) tables in one fell swoop?

五迷三道 提交于 2019-12-11 01:05:36

问题


I have a database with many tables. Twelve of these tables start with the same prefix:

mystuff_table_1
mystuff_table_2
mystuff_table_3
mystuff_table_4
etc...

I don't want to type DROP TABLE mystuff_table_n CASCADE; over and over again, especially since I have to repeatedly drop the tables. How can I make my life easier?


回答1:


First of all, you can delete many tables in a single statement:

DROP TABLE mystuff_table_1, mystuff_table_2, mystuff_table_3 CASCADE;

Next, you could put all of those tables into a separate schema. Add that schema to the default search_path of your user(s), so it's all transparent.

Then all you need is:

DROP SCHEMA foo CASCADE;

If that's not short enough, create a function that executes the command.
A static SQL function:

CREATE OR REPLACE FUNCTION f_delete12()  RETURNS void AS
$func$
DROP TABLE mystuff_table_1, mystuff_table_2, mystuff_table_3, ... CASCADE;
$func$  LANGUAGE sql VOLATILE;

Or a dynamic PL/pgSQL function:

CREATE OR REPLACE FUNCTION f_delete12()
  RETURNS void AS
$func$
BEGIN
EXECUTE (
   SELECT 'DROP TABLE ' || string_agg('mystuff_table_' || g, ', ')
          || ' CASCADE'
   FROM generate_series(1,12) g  -- numbers 1 to 12
   );
END
$func$  LANGUAGE plpgsql VOLATILE;

Call:

SELECT f_delete12();

For an even more dynamic statement:
How do I drop all tables in psql (PostgreSQL interactive terminal) that starts with a common word?




回答2:


you can create a procedure to do this automatically:

Try:

CREATE OR REPLACE FUNCTION public.p_drop_tables (
  p_start integer,
  p_end integer,
  p_table varchar
)
RETURNS void AS
$body$
DECLARE SQL VARCHAR := '';
BEGIN

FOR i IN p_start..p_end LOOP

SQL := 'DROP TABLE public.' || p_table || i || ';';

--RAISE NOTICE '%',SQL;

EXECUTE (SQL);

END LOOP; 

END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

Att



来源:https://stackoverflow.com/questions/22490249/how-to-drop-many-but-not-all-tables-in-one-fell-swoop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!