【问题标题】:How to delete 1 table if another table exists in PostgreSQL using IF-statements如果 PostgreSQL 中存在另一个表,如何使用 IF 语句删除一个表
【发布时间】:2021-01-19 13:13:03
【问题描述】:

如果存在另一个表,我正在尝试编写删除/删除表的查询:

DO
$do$
BEGIN
   IF  EXISTS (SELECT FROM table1) THEN
      DELETE  FROM table2;
    END IF;
END
$do$;

但它所做的只是从 table1 中删除行(如果 table2 存在)而不是表本身。

你可以使用类似于上面的函数吗?或者如果存在的话,我应该使用 drop table 吗?

【问题讨论】:

    标签: sql postgresql stored-procedures drop


    【解决方案1】:

    如果存在另一个表,则删除/删除一个表

    那就是:

    do $$
    begin
        if exists(select 1 from information_schema.tables where table_schema = current_schema() and table_name = 'table1') then
        drop table table2;
      end if;
    end; $$ language plpgsql;
    

    理由:

    • selecting 从表中不是检查它是否存在的正确方法 - 如果不存在,则会引发错误。相反,您可以查询信息架构。

    • 要删除一个表,你需要drop table;另一方面,delete 会删除表格的内容,而不是表格本身。

    【讨论】:

    • 是的!效果很好,只需要在 information_schema 和表格周围添加引号!谢谢。我想知道,选择后的 1 是什么意思?
    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多