【问题标题】:Select all rows with stored procedure使用存储过程选择所有行
【发布时间】:2012-07-16 08:33:15
【问题描述】:

我有一个 postgresql 表:

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

如何使用存储过程返回一组所有单词和 repl。

我试试:

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

谢谢。

【问题讨论】:

    标签: sql postgresql stored-procedures


    【解决方案1】:

    您的函数被定义为只返回一列 (returns text)。此外,您正在读取值的变量也是一个标量,并且不能包含多个值,因此只有单词列被放入 r 变量中。

    您需要将功能更改为例如returns 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;
    

    【讨论】:

      猜你喜欢
      • 2018-11-07
      • 2018-07-10
      • 2017-06-21
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多