数据类型隐式转换规则

本文介绍PolarDB PostgreSQL版(兼容Oracle)数据库数据类型隐式转换规则。

图 1. 隐式转换规则表image.png

  • NA:表示不支持隐式类型转换,例如:

    create table t_smallint(c1 smallint);
    insert into t_smallint select 1;
    select * from t_smallint ;
     c1
    ----
      1
    (1 row)
    
    explain verbose select CAST(c1 as timestamp) from t_smallint;
    ERROR:  cannot cast type smallint to timestamp without time zone
    LINE 1: explain verbose select CAST(c1 as timestamp) from t_smallint...
  • e : 表示仅支持通过CAST::语法进行显示类型转换,例如:

    create table t_timestamp_without_time_zone(c1 timestamp without time zone);
    insert into t_timestamp_without_time_zone values('2021-10-31 08:00:00');
    select CAST(c1 as time without time zone) from t_timestamp_without_time_zone;
        c1
    ----------
     08:00:00
    (1 row)
    
    insert into t_timestamp_without_time_zone values('08:00:00'::time without time zone);
    ERROR:  column "c1" is of type timestamp without time zone but expression is of type time without time zone
    LINE 1: insert into t_timestamp_without_time_zone values('08:00:00':...
                                                             ^
    HINT:  You will need to rewrite or cast the expression.
  • a : 表示除支持e外,还支持隐式向目标列类型赋值(通常指INSERT VALUES赋值或UPDATE SET赋值)。例如:

        create table t_int(c1 integer);
        insert into t_int values(2);
        select cast(c1 as smallint) from t_int;  -- ok
         c1
        ----
          2
        insert into t_int values(3::smallint);  -- ok
  • i : 表示除支持以上a和e外,还支持其他隐式转换,包括如表达式参数等。例如:

        -- case 1
        CREATE OR REPLACE FUNCTION F_VARCHAR(arg1 VarChar) RETURN void
        IS
        BEGIN
           dbms_output.put_line(arg1);
           RETURN;
        END;
    
        SELECT F_VARCHAR(cast('10' as CHAR(10))) FROM DUAL;  -- ok
    
    -- case 2
        create table t_varchar(c1 varchar(10));
        insert into t_varchar values(2);
        explain verbose select sum(c1) from t_varchar;
                                    QUERY PLAN
        ---------------------------------------------------------------------------
        Aggregate  (cost=43.95..43.96 rows=1 width=32)
          Output: sum((c1)::numeric)
          ->  Seq Scan on public.t_varchar  (cost=0.00..29.40 rows=1940 width=14)
               Output: c1