Search code examples
postgresqlplpgsqlset-returning-functions

structure of query does not match function result type postgresql


I have this function which takes a Varchar as an input and it throws a table as an output.

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;

But there is not the problem, the problem is when I execute Select historial_reproductivo_vaca('anything') then I get this message: structure of query does not match function result type I wonder if anyone could help me please. Thanks guys


Solution

  • The error you get stems from the fact that your query returns 8 columns, but your function is defined to return 7.

    Your query to create the temp table returns 7 columns and then you add another column to the table. So your select * returns 8 columns that are matched like this:

    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)                 ?????
    

    Given the result column names and the select column names, it seems you simply forgot to add the (selected) column hierro to the result columns of the function.