postgresql 如何从PostgreSQL数据库中删除表*或*视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/463292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 23:38:14  来源:igfitidea点击:

How to delete table *or* view from PostgreSQL database?

postgresqlplpgsql

提问by Artem Tikhomirov

I have a name of table or view in PostgreSQL database and need to delete in in single pgSQL command. How can i afford it?

我在 PostgreSQL 数据库中有一个表或视图的名称,需要在单个 pgSQL 命令中删除。我怎么买得起?

I was able to select form system table to find out if there any table with such a name but stuck with procedural part:

我能够选择表单系统表以找出是否有任何具有这样名称但卡在程序部分的表:

SELECT count(*) FROM pg_tables where tablename='user_statistics';

回答by empi

DROP TABLE user_statistics;

DROP VIEW user_statistics;

complete syntax:

完整的语法:

DROP TABLE

掉落表

DROP VIEW

下拉视图

And if you want a complete function, i tried something like this:

如果你想要一个完整的功能,我试过这样的事情:

CREATE OR REPLACE FUNCTION delete_table_or_view(objectName varchar) RETURNS integer AS $$
DECLARE
    isTable integer;
    isView integer;
BEGIN
    SELECT INTO isTable count(*) FROM pg_tables where tablename=objectName;
    SELECT INTO isView count(*) FROM pg_views where viewname=objectName;

    IF isTable = 1 THEN
        execute 'DROP TABLE ' || objectName;
        RETURN 1;
    END IF;

    IF isView = 1 THEN
        execute 'DROP VIEW ' || objectName;
        RETURN 2;
    END IF;

    RETURN 0;

END;
$$ LANGUAGE plpgsql;

回答by Magnus Hagander

Consider using DROP TABLE IF EXISTSand DROP VIEW IF EXISTS. That way you won't get an error message if it fails, just a notice.

考虑使用DROP TABLE IF EXISTSDROP VIEW IF EXISTS。这样你就不会在失败时收到错误消息,只是一个通知。