[英]What is the simplest way to return multiple rows from table function in Postgres?
有一個表my_table
我想通過表函數查詢。
create table my_table (
col_1 text,
col_2 numeric
// 10 more columns
);
根據 Internet 上的文檔和文章,有幾種方法可以做到這一點。 但其中大多數涉及定義一個行類型來復制結果表的結構,例如在這種情況下create function ... returns table( col_1 text, col_2 numeric, ...)
。
我發現的最簡單的方法如下:
create or replace function my_func(p_x text)
returns my_table
as
$$
select * from my_table where col_1 = p_x;
$$
language sql;
--
select * from my_func('hello');
不幸的是,它只返回結果的第一行,即使查詢返回很多。 這不是我所期望的。
如果我們將函數頭更改為
create or replace function my_func(p_x text)
returns table( col_1 text, col_2 numeric, /* and others */)
它工作正常,但最好避免這種重復並在此處重用my_table
。
如何定義表結果與my_table
列完全相同的函數?
您需要將該函數定義為returns setof my_table
以指示它返回一個集合,而不僅僅是一行:
create or replace function my_func(p_x text)
returns SETOF my_table
as
$$
select * from my_table where col_1 = p_x;
$$
language sql;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.