【问题标题】:Postgresql: How to work around pseudo-type record errorsPostgresql:如何解决伪类型记录错误
【发布时间】:2022-10-21 01:23:32
【问题描述】:

伪记录错误是一个相当普遍的问题,问题在于让 Postgres 相信它有一个工作行集。有时使用看起来像伪记录但用作完全实体化记录集的中间记录类型可能更容易,并且无需创建和转换为正式的“类型”[记录类型]。

/*
-- This wont work, causes pseudo-type record error
*/
CREATE TEMP TABLE tmpErrPseudoSave AS
SELECT ROW( col2, col1 ) AS anonrow FROM tmpOrigDat ; 

【问题讨论】:

    标签: postgresql casting anonymous-types rowtype recordtype


    【解决方案1】:

    作为PostgreSql 版本。 13有一个体面的解决方法。这是通过将返回集封装为内部查询 CTE 来实现的,外部查询可以看到并将其用作完全物化的状态。

    /**
       we can save it however if we just create the anon row
       but re-expand it right away saving the fields as generic f1, f2 ....
       ( renames every field automatically )
    */
    
    CREATE TEMP TABLE tmpPseudoSave AS
    SELECT (rowrow).* -- expand the anon table struct as f1, f2 .... 
    FROM /** s1 is fully materialized **/
     ( SELECT  ROW( (zz).* ) rowrow FROM (SELECT * FROM  tmpOrigDat ) zz ) s1 
    ;
    

    甚至可以即时将行类型转换为新的兼容类型:

    /* create new but compatible rowtype (could be table-driven from a data dictionary) */

    DROP TABLE IF EXISTS tmpNewRowType;
    CREATE TEMP TABLE tmpNewRowType AS 
      SELECT NULL::CHAR(1) AS zCol1newname2  
            ,NULL::INT AS zCol2newname1 
            LIMIT 0; /** empty object **/
    SELECT * FROM tmpNewRowType ; 
    
    
    SELECT  ((r)::tmpNewRowType).* 
    FROM ( SELECT * FROM tmpPseudoSave ) r /** needs to be encapsulated as a CTE subselect (r)**/
    ;
    

    完整演示dbfiddle.uk

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-27
      • 2013-08-23
      • 1970-01-01
      • 2016-01-25
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多