我在PL / pgSQL中有关于异常的小问题。我的任务是编写一个函数来查找具有一定长度的储层。
我的代码:
create or replace function
info_about_reservoir(num_of_letters int)
returns int as
$$
declare
res_name varchar(50);
res_type varchar(50);
res_area decimal(10,0);
counter int := 1;
begin
select r_name,t_name,r_area into strict res_name,res_type,res_area
from
reservoirs right outer join reservoirs_types
on t_id=r_t_id
where char_length(r_nazwa)=$1;
raise notice 'Name: %, type: %, area: %',res_name,res_type,res_area;
exception
when no_data_found then
raise notice 'No reservoir with name lenght %',$1;
when too_many_rows then
raise notice 'Too much reservoirs with name lenght %',$1;
return counter;
end;
$$ language plpgsql;
对于num_of_letters,必须返回异常: --SELECT info_about_reservoir(7) - no_data_found --SELECT info_about_reservoir(8) - too_many_rows --SELECT info_about_reservoir(9) - 姓名:%...
在此脚本的先前版本中,我只返回了异常和错误:查询没有结果数据的目标。现在它又回来了 7:姓名:...... for 8:Name:来自某些行的第一行查询... for 9:Name:从一行查询行...
对不起,我有一个答案:
create or replace function
info_about_reservoir(num_of_letters int)
returns int as
$$
declare
res_name varchar(50);
res_type varchar(50);
res_area int;
counter int := 1;
begin
select r_name,t_name,r_area into strict res_name,res_type,res_area
from
reservoirs right outer join reservoirs_types
on t_id=a_t_id
where char_length(r_name)=$1;
raise notice 'Name: %, type: %, area: %',res_name,res_type,res_area;
return counter;
exception
when no_data_found then
raise notice 'No reservoir with name lenght %',$1;
return counter;
when too_many_rows then
raise notice 'Too much reservoirs with name lenght %',$1;
return counter;
end;
$$ language plpgsql;
现在它有效。 :d
答案 0 :(得分:1)
基于对缺失的表定义的假设。
最新版本中的RIGHT [OUTER] JOIN
没有用处。由于条件在左表中,您也可以使用[INNER] JOIN
。
你真的想要LEFT JOIN
吗?那么没有匹配的水库类型的水库仍然会被退回吗?
STRICT
modifier in SELECT INTO
仅考虑是否返回单行,它不会对LEFT JOIN
中的缺失行做出反应(或者为单个列分配NULL值。
看起来像:
CREATE OR REPLACE FUNCTION info_about_reservoir(num_of_letters int)
RETURNS int AS
$func$
DECLARE
res_name text;
res_type text;
res_area int;
counter int := 1;
BEGIN
SELECT r_name, t_name, r_area -- no table-qualification for lack of info
INTO STRICT res_name, res_type, res_area
FROM reservoirs r
LEFT JOIN reservoirs_types t ON t_id = a_t_id -- OR JOIN, not RIGHT JOIN
WHERE length(r_name) = $1;
RAISE NOTICE 'Name: %, type: %, area: %', res_name, res_type, res_area;
RETURN counter;
EXCEPTION
WHEN no_data_found THEN
RAISE NOTICE 'No reservoir with name length %.', $1;
RETURN counter;
WHEN too_many_rows THEN
RAISE NOTICE 'Too many reservoirs with name length %.', $1;
RETURN counter;
END
$func$ LANGUAGE plpgsql;
counter
始终为1
。目的是什么?