POSTGRESQL-查询没有结果数据的目的地

时间:2016-12-22 01:04:54

标签: 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;

4 个答案:

答案 0 :(得分:8)

如果在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;

请注意,上述内容仅在查询返回单行时有效。如果查询返回多行,则可以在函数中use a loop。更简单的是,你可以像这样返回查询结果:

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;

但是就像Evan Carroll所说的那样,除非你需要PL / pgSQL函数在返回数据之前修改数据,否则最好用一个简单的视图。

答案 1 :(得分:0)

请使用以下获取给定功能的结果..

create or replace function country(in_parameter text,out out_res refcursor) as $$
begin
open out_res for
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;

答案 2 :(得分:0)

这对SQL来说并不正常。通常,这将是VIEW

CREATE VIEW myView AS
    SELECT customer_id, customer.first_name, customer.last_name 
    FROM customer 
    INNER JOIN address USING (address_id)
    INNER JOIN city USING (city_id)
    INNER JOIN country USING (country_id);

然后你做

 SELECT * FROM myView WHERE country = ?

所有这一切都说,如果你坚持要把它作为一个功能而你不应该,那么你应该把它变为LANAGUAGE SQL而不是LANGUAGE plppsql

答案 3 :(得分:0)

当我的同事在选择查询之前使用 OPEN MYCURS 并且在 返回MYCURS 之后选择查询。

相关问题