【问题标题】:PostgreSQL call function returning setof record with table and additional columnsPostgreSQL 调用函数返回带有表和附加列的记录集
【发布时间】:2021-08-27 09:39:10
【问题描述】:

我正在尝试调用一个函数,返回现有表的所有列 + 一些不相关的附加列,并使用以下语法检索返回的数据:

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.

【问题讨论】:

  • 使用包含表名的实际列名,而不是 SELECT mtn.*
  • @Shameel 我不明白。那么如何选择所有表格列?

标签: sql postgresql stored-functions


【解决方案1】:

如果你的函数中的查询应该返回一个my_table_name(一个“整行引用”),你应该这样写

SELECT mtn, count(*) OVER () ...

【讨论】:

    猜你喜欢
    • 2012-06-08
    • 2019-02-14
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    相关资源
    最近更新 更多