kim*_*n12 3 postgresql postgresql-9.3
我是postgres和编程的新手,我已经为此寻找解决方案,但我无法理解.我正在尝试创建一个函数,只要我呼叫该国家,就会返回有关该特定国家/地区所有客户的信息.这是弹出的错误.我真的很抱歉这个问题,但我从昨天开始就被困在这里.
错误:查询没有结果数据的目的地
提示:如果要丢弃SELECT的结果,请改用PERFORM.
语境:SQL语句中的PL/pgSQL函数country(text)第5行
这是功能:
create or replace function country(text) returns text as $$
begin
select customer_id, customer.first_name, customer.last_name
from customer
inner join address on customer.address_id = address.address_id
inner join city on address.city_id = city.city_id
inner join country on city.country_id = country.country_id
where country = '$1';
end;
$$
language plpgsql;
Run Code Online (Sandbox Code Playgroud)
如果在PL/pgSQL函数中执行select语句,则应将查询结果放在某个变量(=目标)中.然后使用函数中的变量.你还应该有一份RETURN声明.
create or replace function country(text) returns text as $$
declare -- declare some variables
id integer;
fname text;
lname text;
begin
select customer_id, customer.first_name, customer.last_name
into id, fname, lname -- store query results in variables
from customer
inner join address on customer.address_id = address.address_id
inner join city on address.city_id = city.city_id
inner join country on city.country_id = country.country_id
where country = $1; -- don't quote parameter references
-- do something with the variables and return a value from the function
return format('%s: %s %s', id, upper(lname), fname);
end;
$$ language plpgsql;
Run Code Online (Sandbox Code Playgroud)
请注意,只有在查询返回单行时,上述操作才有效.如果查询返回多行,则可以在函数中使用循环.更简单的是,您可以从查询中返回结果,如下所示:
create or replace function country(text)
returns table (id integer, first_name varchar, last_name varchar) as $$
begin
return query
select customer_id, customer.first_name, customer.last_name
from customer
inner join address on customer.address_id = address.address_id
inner join city on address.city_id = city.city_id
inner join country on city.country_id = country.country_id
where country = $1;
end;
$$ language plpgsql;
Run Code Online (Sandbox Code Playgroud)
但是就像Evan Carroll所说的那样,除非你需要PL/pgSQL函数来修改数据才能返回它,你最好用一个简单的视图.
| 归档时间: |
|
| 查看次数: |
14910 次 |
| 最近记录: |