我有一个可以返回 0、1 或更多行的查询。
这是我的功能:
CREATE OR REPLACE FUNCTION A(v_x integer[])
RETURNS void AS
$BODY$
declare
x_part integer;
x_part2 integer;
x_sum integer;
begin
select a,b,sum(qty) into x_part, x_part2,x_sum
from tablet
where location= any (v_x)
group by a,b
..... more actions....
end;
$BODY$
LANGUAGE plpgsql VOLATILE
我有两个问题:
如果查询返回多行,我无法将结果保存到
x_part,x_part2,x_sum
。如何知道返回的行数?
基本上我需要的是,如果有超过 1 行要退出带有错误消息的函数,如果有 1 行或 0 行.. 继续函数操作。
我该怎么做?
最佳答案
您可以在 SELECT INTO 行中使用关键字 STRICT 执行此操作,如下所述:http://www.postgresql.org/docs/9.1/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW在 postgresql 手册中。
基本上你的电话变成了:
select a,b,sum(qty) into STRICT x_part, x_part2,x_sum from tablet where location= any (v_x) group by a,b;
... -- Rest of your function code here
-- Exception block added at the end of the code, only called if there is an exception anywhere within your function
EXCEPTION
WHEN TOO_MANY_ROWS THEN
RAISE EXCEPTION 'Too many rows!';
end
$$ LANGUAGE plpgsql;
**也许另一种解决方案是在查询末尾添加一个 LIMIT 1 以保证返回的行不超过一行?虽然这可能掩盖了一个问题? ** - 将其留在此处作为注释引用,但承认在这种情况下这不是有效选项
HTH
关于sql - 在 postgresql 中。我怎么知道查询是否返回超过 1 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34130097/