查询在智能检查失败时抛出错误
问题描述:
在编写旨在通过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
声明的详细信息,请参阅手册:
http://www.postgresql.org/docs/current/static/plpgsql-errors-and-messages.html
答
你可以做到这一点作为一个存储过程/函数将您想要执行的查询作为参数。 在checkif bad_foo有0条记录的过程中,然后执行查询。否则你退出。
如果你想检查是否存在一行,可能是:“select case exists when exists(select from foo where is_bad_foo)then 1 else 0 end;” –