我试图根据条件在启动时删除表:
IF NOT EXISTS (select * from pg_class where relname = 'mytable' and relpersistence = 'u')
DROP TABLE IF EXISTS mytable
结果:Syntaxerror at 'IF', SQL state: 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条件中包括模式名称,以确保您不会意外从错误的模式中删除表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句