Postgresql 在健全性检查失败时引发错误的查询

Postgresql 在健全性检查失败时引发错误的查询,postgresql,Postgresql,在编写拟通过psql复制/粘贴或通过“\i”运行的脚本时,我希望包括一个健全性检查-如果某个查询返回任何行,事务应中止- select * from foos where is_bad_foo; -- Abort transaction if any results 实现这一点的好方法是什么?将其放入函数或匿名块中: do $$ declare l_count integer; begin select count(*) into l_count from foo w

在编写拟通过psql复制/粘贴或通过“\i”运行的脚本时,我希望包括一个健全性检查-如果某个查询返回任何行,事务应中止-

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

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

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

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语句的详细信息,请参阅手册:

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

若你们想检查一行的存在性,也许:选择case when exists从foo选择null where is_bad_foo然后选择1 else 0 end;