database – 如何根据postgres中的IF条件删除表?

前端之家收集整理的这篇文章主要介绍了database – 如何根据postgres中的IF条件删除表?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图根据条件在启动时删除一个表:

IF NOT EXISTS (select * from pg_class where relname = 'mytable' and relpersistence = 'u') 
DROP TABLE IF EXISTS mytable

结果:’IF’处的语法错误,sql状态:42601.为什么?如果我不被允许使用IF,我如何根据条件删除表格?

解决方法

IF不能在sql中使用,这仅对PL / pgsql有效.

您需要在匿名PL / pgsql块中使用动态sql执行此操作.就像是:

do
$$
declare
  l_count integer;
begin
  select count(*)
     into l_count
  from pg_class c
    join pg_namespace nsp on c.relnamespace = nsp.oid
  where c.relname = 'mytable' 
    and c.relpersistence = 'u'
    and nsp.nspname = 'public';

  if l_count = 1 then 
    execute 'drop table mytable';
  end if;

end;
$$

您可能应该将select语句扩展为针对pg_namespace加入,并在where条件中包含模式名称,以确保您不会意外地从错误的模式中删除表.

猜你在找的Postgre SQL相关文章