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関数を必要としない限り、あなたはシンプルでオフに優れている、言った:でもシンプルな、あなただけそうのようなクエリから結果を返すことができますビュー。
あなたはクエリを実行していますが、プロキシから何も返されません。どのようにして 'language sql'を使用するのかについては、ここの例で示されています。https://www.postgresql.org/docs/9.2/static/xfunc-sql.html – Glenn
これをsqlに変更しました。これがエラーをポップアップ表示します。または近い "選択" 行5:select customer_id、customer.first_name、customer.last_name ^ 本当に混乱している – kimdasuncion12
例を注意深く見てください。 35.4.4にはシナリオに合った例があります。最初に実行してから、必要なものに変更することができます。この例の 'language sql'は' begin'や 'end'を持たず、' out'パラメータを持っています。 – Glenn