0

私はpostgresqlテーブルを持っています:

|  words  |  repl |
|  word1  | repl1 |
|  word2  | repl2 |
|  word3  | repl3 |    

すべての単語のセットを返し、ストアドプロシージャを使用するにはどうすればよいですか。

私は試してみます:

create function get_words() returns setof text as
$$
declare
    r varchar;
begin
  for r in
      select word,repl from my_table
      loop
        return next r;
    end loop;
    return;
end
$$ language plpgsql;

私がそれを実行するとき、私は単語だけを得ました:

select * from get_words();
 get_words 
-----------
 word1
 word2
 word3

ありがとうございました。

4

1 に答える 1

1

関数は、1 つの列 ( returns text) のみを返すように定義されています。さらに、値を読み込んでいる変数もスカラーであり、複数の値を保持できないため、列という単語だけが変数に入れられrます。

関数を egreturns set of my_tableに変更し、ループ変数の定義を変更する必要があります。

create or replace function get_words() 
   returns setof my_table as
$$
declare
    r words%rowtype;
begin
  for r in select w.word, w.repl from my_table w
  loop
     return next r;
  end loop;
  return;
end
$$ language plpgsql;

ループ内で何もするつもりがない場合は、次を使用return queryすると少し簡単になります。

create or replace function get_words() 
  returns table (word text, repl text)
as
$$
begin
  return query select w.word, w.repl from words w;
end
$$ language plpgsql;

PL/pgSQL を使用せずに単純な SQL 関数を使用する場合、これをさらに短縮できます。

create or replace function get_words() 
   returns table (word text, repl text)
as
$$
  select w.word, w.repl from words w;
$$ language sql;
于 2012-07-16T09:01:58.833 に答える