如何停止 PostgreSQL 的 SQL 脚本执行?

Pau*_*est 6 sql postgresql

PostgreSQL中有创建表的DDL脚本。

例如,如果第一个表存在, 如何停止 PostgreSQL 的 SQL 脚本执行(在脚本内)?

小智 3

如果您想根据条件中止脚本,您可以使用DO引发错误的块来实现:

do
$$
declare 
  l_count integer;
begin

  select count(*)
     into l_count
  from information_schema.tables
  where table_name = 'foobar'
    and table_schema = 'public';

  if (l_count > 0) then 
     raise exception 'Table foobar already exists!';
  end if;
end;
$$
Run Code Online (Sandbox Code Playgroud)

这要求您的 SQL 客户端在发生错误时中止脚本。


另一种选择是更改脚本,以便在表已存在时使用create table if not exists .....

但这取决于您到底想要实现什么目标。