【问题标题】:Structure of query does not match function result type, RETURNS TABLE查询结构与函数结果类型不匹配,RETURNS TABLE
【发布时间】:2013-02-04 20:30:53
【问题描述】:

我需要一个简单的函数来返回动态的列集。我在 SO 上找到了几个示例,结果如下:

CREATE or replace FUNCTION getColumn(_column1 text, _column2 text, _column3 text, _table text)
  RETURNS TABLE(cmf1 text, cmf2 text, cmf3 text) AS $$
BEGIN
    RETURN QUERY EXECUTE 
        'SELECT ' 
            || quote_ident(_column1)::text || ' as cmf1,'
            || quote_ident(_column2)::text || ' as cmf2,'
            || quote_ident(_column3)::text || ' as cmf3'
        ' FROM '
            || quote_ident(_table); 
END;
 $$ LANGUAGE plpgsql;

我需要这个函数只适用于 varchar/text 列,所以我创建了这个测试表:

create table test20130205 (
    a text,
    b text,
    c varchar,
    d text)
;

最后,我可以运行一些测试:

select * from getColumn('a','b','d','test20130205');
-- ok
select * from getColumn('a','b','c','test20130205');
-- error
ERROR:  structure of query does not match function result type
DETAIL:  Returned type character varying does not match expected type text in column 3.
CONTEXT:  PL/pgSQL function getcolumn(text,text,text,text) line 3 at RETURN QUERY

似乎在强制转换之前检查了列 c (varchar) 的类型 - 这看起来很奇怪,但我想我错过了一些东西。

如何修复我的功能?

(PostgreSQL 9.1)

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    在您当前的函数中,对文本的强制转换不适用于输出列的值,它们适用于它们的名称(quote_ident 的结果)。

    演员应该在查询本身内部移动:

    CREATE or replace FUNCTION getColumn(_column1 text, _column2 text, _column3 text, _table text)
      RETURNS TABLE(cmf1 text, cmf2 text, cmf3 text) AS $$
    BEGIN
        RETURN QUERY EXECUTE 
            'SELECT ' 
                || quote_ident(_column1) || '::text as cmf1,'
                || quote_ident(_column2) || '::text as cmf2,'
                || quote_ident(_column3) || '::text as cmf3'
            ' FROM '
                || quote_ident(_table); 
    END;
     $$ LANGUAGE plpgsql;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多