【问题标题】:Drop table if it has less than n records如果表的记录少于 n 则删除表
【发布时间】:2016-03-21 18:40:31
【问题描述】:

我正在尝试使用postgres,但无法让这个简单的查询工作:

drop table mytable if (select count(*) from mytable)<50 ;

这给出了错误:

ERROR:  syntax error at or near "if"
LINE 1: drop table tablename if (select count(*) from mytable)<50 ;

在给定条件下如何更改/删除 postgres 中的表?

【问题讨论】:

标签: sql postgresql postgresql-9.4 drop-table


【解决方案1】:

为此创建动态 SQL 有效(参见 answer)-

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 nsp.nspname = 'public';
  if l_count < 50 then 
    execute 'drop table mytable';
  end if;
end;
$$

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多