我正在寻找有关返回表格的PostgreSQL函数的帮助。 我想知道是否有更新正在返回的表的方法。
这是一个例子,
create or replace function fn_function()
return table(column01 integer, column02 integer, column03 boolean) as $$
return query
select col1, col2, false
from tableXYZ;
/* how can i update the table, let's say column03 before the function exits */
end
$$ language plpgsql;
我可以为要返回的表提供别名吗?
使用的postgre版本是9.0.8。
提前谢谢。答案 0 :(得分:0)
这是一个基于集合的解决方案。
RETURNS TABLE只是获取数据的门户,您无法在定义它的函数内执行任何操作。您可以创建另一个函数并调用此函数并对结果集执行操作。但是我使用临时表,因此您可以在发送数据之前对其进行操作。
CREATE OR REPLACE FUNCTION fn_function()
RETURNS TABLE(column01 integer, column02 integer, column03 boolean) AS $$
BEGIN
CREATE TEMP TABLE temp_tableXYZ (column01 integer, column02 integer, column03 boolean) ON COMMIT DROP;
INSERT INTO temp_tableXYZ (column01, column02, column03)
SELECT col1,col2,col3
FROM tableXYZ;
--WHERE filter if you can.
UPDATE temp_tableXYZ
SET col1 = 9999;
RETURN QUERY select column01, column02, column03 from temp_tableXYZ;
END;
$$ LANGUAGE plpgsql;
你可以使用这样的别名来调用它:
SELECT * FROM fn_function() as my_table;
答案 1 :(得分:0)
只需执行一个返回所需值的查询。它可以是简单的sql:
create or replace function fn_function()
returns table (
column01 integer, column02 integer, column03 boolean
) as $$
select col1, col2, col2 > 10
from tableXYZ;
$$ language sql;
在上面的例子中,如果col2>列3将为真。 10,否则为假。使用子选择的另一个例子:
create or replace function fn_function()
returns table (
column01 integer, column02 integer, column03 boolean
) as $$
select col1, col2, (select max(col1) > 10 from t where col2 = tableXYZ.col1)
from tableXYZ;
$$ language sql;
请注意,它不是return
而是returns
答案 2 :(得分:0)
要从表中进行选择,请修改select的结果并将其作为函数的结果传递,如下所示:
create or replace function fn_function()
returns table (
column01 integer, column02 integer, column03 boolean
) as $$
begin
for rec in select col1, col2, false as col3
from tableXYZ;
loop
rec.col3 := col1 > col2;
return next rec;
end loop;
return;
end
$$ language plpgsql;
详情here
。
要选择获取此功能的结果,只需
SELECT function_alias.col1, function_alias.col2
FROM fn_function() function_alias;
您可以使用此功能执行与普通表相同的操作。