如果健全性检查失败,则查询以抛出错误

时间:2015-09-04 21:20:23

标签: postgresql

在编写一个旨在通过psql(复制/粘贴或通过'\ i')运行的脚本时,我想包括一个完整性检查 - 如果某个查询返回任何行,事务应该中止 -

select * from foos where is_bad_foo;  -- Abort transaction if any results

实现这一目标的好方法是什么?

2 个答案:

答案 0 :(得分:4)

将它放入函数或匿名块中:

do
$$
declare
  l_count integer;
begin
  select count(*)
    into l_count
  from foo
  where is_bad_foo;
  if (l_count > 0) then
    raise exception 'too may rows';
  end if;
end;
$$

有关raise声明的详细信息,请参阅手册:
http://www.postgresql.org/docs/current/static/plpgsql-errors-and-messages.html

答案 1 :(得分:0)

您可以将此作为存储过程/函数执行此操作,该存储过程/函数将您要执行的查询作为参数执行。 在程序内你检查bad_foo有0条记录,然后执行查询。否则你退出。