2012-07-16 68 views
0

选中所有行我有一个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 

谢谢。

回答

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;