查询结构与函数结果类型 postgresql 不匹配

Posted

技术标签:

【中文标题】查询结构与函数结果类型 postgresql 不匹配【英文标题】:structure of query does not match function result type postgresql 【发布时间】:2020-05-08 01:43:19 【问题描述】:

我有这个函数,它接受一个 Varchar 作为输入,它抛出一个表作为输出。

create or replace function historial_reproductivo_vaca(hierro_v varchar) returns table(hierro_toro varchar, sexo varchar, fecha_nacimiento varchar, peso_nacimiento numeric, peso_destete numeric, clasificacion varchar, estado varchar)
as $$
    declare
        estado varchar;
    begin 
        create temporary table temp_table AS
        select hijos.hierro_padre as toro, hijos.sexo as s, hijos.fecha_nacimiento as nacimiento, hijos.hierro as hierro, pesos.peso_nacimiento, pesos.peso_12_meses, hijos.clasificacion FROM
        ((select animales.hierro, animales.sexo, animales.fecha_nacimiento, animales.hierro_madre, animales.hierro_padre, animales.clasificacion from animales) 
        union (select defuncion.hierro, defuncion.sexo, defuncion.fecha_nacimiento, defuncion.hierro_madre, defuncion.hierro_padre, defuncion.clasificacion from defuncion) 
        union (select venta_carne.hierro, venta_carne.sexo, venta_carne.fecha_nacimiento, venta_carne.hierro_madre, venta_carne.hierro_padre, venta_carne.clasificacion from venta_carne) 
        union (select venta_finca.hierro, venta_finca.sexo, venta_finca.fecha_nacimiento, venta_finca.hierro_madre, venta_finca.hierro_padre, venta_finca.clasificacion from venta_finca))as hijos
        JOIN pesos ON pesos.hierro = hijos.hierro;
        alter table temp_table add estado varchar;
        --call update_temp_table(temp_table.hierro) from temp_table;
        return QUERY SELECT * from temp_table;
    end;
$$ language plpgsql;

但是没有问题,问题是当我执行Select historial_reproductivo_vaca('anything') 然后我得到这个消息:structure of query does not match function result type 我想知道是否有人可以帮助我。谢谢大家

【问题讨论】:

欢迎使用 ***。参观并获得您的第一个徽章-***.com/tour 在 Postgres 中通常不需要在临时表中存储中间结果。无论您在“更新临时表”中做什么,都可以直接在 QUERY 本身中更有效地完成 与您的问题无关,但是:由于您的函数定义为returns table,您应该像使用表格一样使用它并将其放入 FROM 子句中:select * from historial_reproductivo_vaca(..) 【参考方案1】:

您得到的错误源于您的查询返回 8 列,但您的函数定义为返回 7。

创建临时表的查询返回 7 列,然后向表中添加另一列。因此,您的 select * 返回 8 列匹配如下:

selected column (from temp table)     declared output column
---------------------------------------------------------------
toro                                  hierro_toro
s                                     sexo
nacimiento                            fecha_nacimiento
hierro                                peso_nacimiento
peso_nacimiento                       peso_destete
peso_12_meses                         clasificacion
clasificacion                         estado
estado (added column)                 ?????

鉴于结果列名和选择列名,您似乎只是忘记将(选定)列hierro 添加到函数的结果列中。

【讨论】:

以上是关于查询结构与函数结果类型 postgresql 不匹配的主要内容,如果未能解决你的问题,请参考以下文章

“查询结构与函数结果类型不匹配。返回类型双精度与第 1 列中的预期类型整数不匹配。”?

将时间戳与查询中的日期名称相等,并在 PostgreSQL 查询中获取结果集 w.r.t 日期名称

显示查询结果列类型 (PostgreSQL)

PostGreSQL Json数据存储和条件查询

PostgreSQL——查询分析

PostgreSQL---语义分析