私はpostgresとプログラミングに不慣れで、すでにこれに対する解決策を探していましたが、完全には理解できませんでした。その国に電話をかけるたびに、その国のすべての顧客に関する情報を返す関数を作成しようとしています。これはポップアップするエラーです。本当に申し訳ありませんが、昨日からここで立ち往生しています。
エラー:クエリに結果データの宛先がありません
ヒント:SELECTの結果を破棄する場合は、代わりにPERFORMを使用してください。
CONTEXT: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;
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;
上記は、クエリが単一の行を返す場合にのみ機能することに注意してください。クエリが複数の行を返す場合は、関数で ループを使用 できます。さらに簡単に、次のようにクエリから結果を返すことができます。
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関数が必要でない限り、単純なビューを使用する方がよいでしょう。
同僚が選択クエリの前にOPEN MYCURSを使用し、RETURN MYCURS選択クエリの後。
与えられた機能の結果を得るために以下を使用してください。
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;
これは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
。