PostgreSQL 调用函数返回带有 table 和附加列的记录集
PostgreSQL call function returning setof record with table and additional columns
我正在尝试调用一个函数,返回现有 table 的所有列 + 一些不相关的附加列,并使用以下语法检索返回的数据:
select *
from test_func(...)
as (a_table my_table_name, rows_count numeric);
函数格式如下:
CREATE OR REPLACE FUNCTION public.test_func(...)
RETURNS SETOF record
LANGUAGE plpgsql
AS $function$
DECLARE
_sql VARCHAR;
begin
_sql := 'SELECT mtn.*, count(*) over() as rows_count
from public.my_table_name mtn
... inner joins and other stuff';
return query
execute _sql using ..._sql params...;
END;
$function$
;
然而,它不起作用。我收到的错误:
ERROR: structure of query does not match function result type
Detail: Returned type numeric does not match expected type "my_table_name" in column 1.
如果你的函数中的查询应该return一个my_table_name
(一个“整行引用”),你应该这样写
SELECT mtn, count(*) OVER () ...
我正在尝试调用一个函数,返回现有 table 的所有列 + 一些不相关的附加列,并使用以下语法检索返回的数据:
select *
from test_func(...)
as (a_table my_table_name, rows_count numeric);
函数格式如下:
CREATE OR REPLACE FUNCTION public.test_func(...)
RETURNS SETOF record
LANGUAGE plpgsql
AS $function$
DECLARE
_sql VARCHAR;
begin
_sql := 'SELECT mtn.*, count(*) over() as rows_count
from public.my_table_name mtn
... inner joins and other stuff';
return query
execute _sql using ..._sql params...;
END;
$function$
;
然而,它不起作用。我收到的错误:
ERROR: structure of query does not match function result type
Detail: Returned type numeric does not match expected type "my_table_name" in column 1.
如果你的函数中的查询应该return一个my_table_name
(一个“整行引用”),你应该这样写
SELECT mtn, count(*) OVER () ...