无论类型如何删除视图 (Postgres)

Drop View Regardless of Type (Postgres)

我正在尝试将实体化视图转换为视图。由于我们的模式是如何部署的,我必须想出一个 SQL 脚本来删除 table 名称中的任何内容,然后重新创建视图。但是,我在重新 运行 这段代码时收到错误消息,指出该视图不是物化视图,我需要改用 DROP VIEW。有办法解决这个问题吗? DROP VIEW 也会删除物化视图吗?

您可以使用函数:

create or replace function drop_any_view(regclass)
returns void language plpgsql as $$
begin
    execute format(
        'drop %s view %s', 
            case (select relkind from pg_class where oid = )
            when 'm' then 'materialized'
            else '' end,
            
        );
end $$;

该函数删除一个视图,无论它是否具体化。

select drop_any_view('my_view');