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

时间:2016-12-18 04:43:35

标签: postgresql plpgsql

将类型(通过强制转换)从bigint更改为text后,我的PLPGSQL函数停止工作。这是我得到的错误:

dev=> select * from app.get_companies(4,808739954140037) ;
NOTICE:  Data rows were NOT found (structure of query does not match function result type)
 company_id_str | company_name 
----------------+--------------
(0 rows)

dev=> 

这是我的职责:

CREATE OR REPLACE FUNCTION app.get_companies(ident_id bigint,sess bigint)
RETURNS TABLE(company_id_str text,company_name text) as $$
DECLARE
    server_session bigint;
BEGIN
    select app.session.session from app.session where app.session.identity_id=ident_id and app.session.session=sess into server_session;
    IF FOUND
    THEN
        BEGIN
            RETURN QUERY SELECT quote_ident(app.company.company_id::text)::text as company_id_str,app.company.name as company_name FROM app.company,app.identcomp WHERE app.company.company_id=app.identcomp.company_id and app.identcomp.identity_id=ident_id;
        EXCEPTION
            WHEN OTHERS THEN
                RAISE NOTICE 'Data rows were NOT found (%)',SQLERRM;
                RETURN;

        END;
    ELSE
        RAISE NOTICE 'Session row was NOT found';
        RETURN;
    END IF;
END;
$$ LANGUAGE plpgsql;

如果我正在应用强制转换并且我将输出定义为TABLE,为什么会发生此错误?

app.company表定义为:

create table app.company (
    company_id          bigserial,
    date_inserted       timestamp,
    name                varchar(64)
);

2 个答案:

答案 0 :(得分:1)

app.company.namevarchar(64),而返回表格的company_nametext。将app.company.name投射到text

如果你没有在函数体中捕获异常(为什么?),你会得到更详细的错误信息:

ERROR:  structure of query does not match function result type
DETAIL:  Returned type character varying(64) does not match expected type text in column 2.

答案 1 :(得分:0)

如果要更改现有功能的返回类型,则需要删除现有功能,然后再次创建相同的功能。

要删除该功能:

DROP FUNCTION [ IF EXISTS ] name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
[ CASCADE | RESTRICT ]