ORACLE隐式类型转换

 

隐式类型转换简介

 

通常oracle数据库存在显式类型转换(explicit datatype conversion和隐式类型转换(implicit datatype conversion)两种类型转换方式。如果进行比较或运算的两个值的数据类型不同时(源数据的类型与目标数据的类型),而且此时又没有转换函数时,那么oracle必须将其中一个值进行类型转换,使其能够运算。这就是所谓的隐式类型转换。其中隐式类型转换是自动进行的,当然,只有在这种转换是有意义的时候,才会自动进行。

 

data conversion

generally an expression cannot contain values of different datatypes. for example, an expression cannot multiply 5 by 10 and then add ‘james’. however, oracle supports both implicit and explicit conversion of values from one datatype to another.

 

 

关于隐式类型转换,建议翻看官方文档data type comparison rules章节,下面是官方文档中的隐式类型转换矩阵。从下面这个表格,我们就能对哪些数据类型能进行转换一目了然。

 

 

 

 

 

隐式转换的规则:

 

 

其实隐式类型转换发生在很多地方,只是我们很多时候没有留意罢了,不打算一一举例,自行翻阅官方文档的介绍,摘抄隐式类型转换的一些常见的规则如下:

 

the following rules govern implicit data type conversions:

  • during insert and update operations, oracle converts the value to the data type of the affected column.
  • during select from operations, oracle converts the data from the column to the type of the target variable.
  • when manipulating numeric values, oracle usually adjusts precision and scale to allow for maximum capacity. in such cases, the numeric data type resulting from such operations can differ from the numeric data type found in the underlying tables.
  • when comparing a character value with a numeric value, oracle converts the character data to a numeric value.
  • conversions between character values or number values and floating-point number values can be inexact, because the character types and number use decimal precision to represent the numeric value, and the floating-point numbers use binary precision.
  • when converting a clob value into a character data type such as varchar2, or converting blob to raw data, if the data to be converted is larger than the target data type, then the database returns an error.
  • during conversion from a timestamp value to a date value, the fractional seconds portion of the timestamp value is truncated. this behavior differs from earlier releases of oracle database, when the fractional seconds portion of the timestamp value was rounded.
  • conversions from binary_float to binary_double are exact.
  • conversions from binary_double to binary_float are inexact if the binary_double value uses more bits of precision that supported by the binary_float.
  • when comparing a character value with a date value, oracle converts the character data to date.
  • when you use a sql function or operator with an argument of a data type other than the one it accepts, oracle converts the argument to the accepted data type.
  • when making assignments, oracle converts the value on the right side of the equal sign (=) to the data type of the target of the assignment on the left side.
  • during concatenation operations, oracle converts from noncharacter data types to char or nchar.
  • during arithmetic operations on and comparisons between character and noncharacter data types, oracle converts from any character data type to a numeric, date, or rowid, as appropriate. in arithmetic operations between char/varchar2 and nchar/nvarchar2, oracle converts to a number.
  • most sql character functions are enabled to accept clobs as parameters, and oracle performs implicit conversions between clob and character types. therefore, functions that are not yet enabled for clobs can accept clobs through implicit conversion. in such cases, oracle converts the clobs to char or varchar2 before the function is invoked. if the clob is larger than 4000 bytes, then oracle converts only the first 4000 bytes to char.
  • when converting raw or long raw data to or from character data, the binary data is represented in hexadecimal form, with one hexadecimal character representing every four bits of raw data. refer to “raw and long raw data types” for more information.
  • comparisons between char and varchar2 and between nchar and nvarchar2 types may entail different character sets. the default direction of conversion in such cases is from the database character set to the national character set. table 2-9 shows the direction of implicit conversions between different character types.

 

对上面官方文档资料的翻译如下,如有不对或不够确切的地方,敬请指出

 

1.  对于insertupdate操作,oracle会把插入值或者更新值隐式转换为对应字段的数据类型。

 

2.  对于select语句,oracle会把字段的数据类型隐式转换为变量的数据类型。

 

3.  当处理数值时,oracle通常会调整精度和小数位,以实现最大容量。在这种情况下,由此类操作产生的数字数据类型可能与在基础表中找到的数字数据类型不同。

 

4.  当比较一个字符型和数值型的值时,oracle会把字符型的值隐式转换为数值型。

 

5.  字符值或number值与浮点数值之间的转换可能不准确,因为字符类型和number使用十进制精度表示数字值,而浮点数则使用二进制精度。

 

6.  clob值转换为字符数据类型(例如varchar2)或将blob转换为raw数据时,如果要转换的数据大于目标数据类型,则数据库将返回错误。

 

7.   timestamp类型转换为date时(按照第三条,隐式转换不应该把timestamp转换为date,除非insert这样的),timestamp后几位会被truncated忽略,至于忽略几位,取决于数据库版本。

 

8.  binary_floatbinary_double的转换是准确的。

 

9.  binary_doublebinary_float的转换是不精确的,因为binary_double精度更高。

 

10.  当比较字符型和日期型的数据时,oracle会把字符型转换为日期型。

 

11. 如果调用函数(过程)或运算符操作时,如果输入参数的数据类型与函数(存储过程)定义的参数数据类型不一致或不是可接受的数据类型时,则oracle会把输入参数的数据类型转换为函数或者过程定义的数据类型。

 

12. 当使用赋值符号(等号)时,右边的类型转换为左边的类型

 

13. 当连接操作(concatenation,一般为||)时,oracle会隐式转换非字符型到字符型

 

14. 如果字符类型的数据和非字符类型的数据(numberdaterowid)作算术运算,则oracle会将字符类型的数据转换为合适的数据类型,这些数据类型可能是numberdaterowid等。

  如果char/varchar2 nchar/nvarchar2之间作算术运算,则oracle会将她们都转换为number类型的数据再做比较。

 

 

15. 比较char/varchar2 nchar/nvarchar2时,如果两者字符集不一样,则默认的转换方式是将数据编码从数据库字符集转换为国家字符集

 

 

下面简单举两个例子,看看隐式转换发生的场景:

 

例子:

 

sql> create table test(object_id varchar2(12), object_name varchar2(64));
 
table created.
 
sql> insert into test
  2  select object_id, object_name from dba_objects;
 
63426 rows created.
 
sql> commit;
 
commit complete.
 
sql> create index ix_test_n1 on test(object_id);
 
index created.
 
sql> select count(*) from test where object_id=20;
 
  count(*)
----------
         1
 
sql> select * from table(dbms_xplan.display_cursor);
 
plan_table_output
-------------------------------------------------------------------------------
sql_id  4bh7yzj5ma0ks, child number 0
-------------------------------------
select count(*) from test where object_id=20
 
plan hash value: 1950795681
 
---------------------------------------------------------------------------
| id  | operation          | name | rows  | bytes | cost (%cpu)| time     |
---------------------------------------------------------------------------
|   0 | select statement   |      |       |       |    45 (100)|          |
|   1 |  sort aggregate    |      |     1 |     8 |            |          |
 
plan_table_output
-------------------------------------------------------------------------------
|*  2 |   table access full| test |     3 |    24 |    45  (20)| 00:00:01 |
---------------------------------------------------------------------------
predicate information (identified by operation id):
---------------------------------------------------
   2 - filter(to_number("object_id")=20)
 
note
-----
   - dynamic sampling used for this statement
 
plan_table_output
-------------------------------------------------------------------------------------
 
23 rows selected.

 

如上所示,这个发生隐式转换是因为这个规则: 当比较一个字符型和数值型的值时,oracle会把字符型的值隐式转换为数值型(对于select语句,oracle会把字段的数据类型隐式转换为变量的数据类型。似乎这个规则也对),此时由于隐式转换发生在object_id字段上(to_number(“object_id”),导致执行计划走全表扫描。如果我们稍微修改一下sql的写法,就会发现执行计划会走index range scan。 如下所示:

 

sql>  select count(*) from test where object_id='20';
 
  count(*)
----------
         1
 
sql> select * from table(dbms_xplan.display_cursor);
 
plan_table_output
--------------------------------------------------------------------------------
sql_id  7800f6da7c909, child number 0
-------------------------------------
 select count(*) from test where object_id='20'
 
plan hash value: 4037411162
 
--------------------------------------------------------------------------------
| id  | operation         | name       | rows  | bytes | cost (%cpu)| time     |
--------------------------------------------------------------------------------
|   0 | select statement  |            |       |       |     1 (100)|          |
|   1 |  sort aggregate   |            |     1 |     6 |            |          |
 
plan_table_output
--------------------------------------------------------------------------------
|*  2 |   index range scan| ix_test_n1 |     1 |     6 |     1   (0)| 00:00:01 |
--------------------------------------------------------------------------------
predicate information (identified by operation id):
---------------------------------------------------
   2 - access("object_id"='20')
 
 
19 rows selected.

 

下面再介绍一个案例(当比较字符型和日期型的数据时,oracle会把字符型转换为日期型。),这种转换虽然大部分情况下都是正常的,但是有时候会成为一个隐藏的逻辑炸弹,当nls_date_format环境变量改变时,则有可能出现错误或逻辑错误。

 

sql> select *
  2  from scott.emp
  3  where hiredate between '01-jan-1981' and '01-apr-1981';
 
     empno ename      job              mgr hiredate         sal       comm     deptno
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7499 allen      salesman        7698 20-feb-81       1600        300         30
      7521 ward       salesman        7698 22-feb-81       1250        500         30
 
sql> select * from table(dbms_xplan.display_cursor);
 
plan_table_output
----------------------------------------------------------------------------------
sql_id  czyc76busj56d, child number 0
-------------------------------------
select * from scott.emp where hiredate between '01-jan-1981' and
'01-apr-1981'
 
plan hash value: 3956160932
 
--------------------------------------------------------------------------
| id  | operation         | name | rows  | bytes | cost (%cpu)| time     |
--------------------------------------------------------------------------
|   0 | select statement  |      |       |       |     2 (100)|          |
 
plan_table_output
--------------------------------------------------------------------------
|*  1 |  table access full| emp  |     2 |    74 |     2   (0)| 00:00:01 |
--------------------------------------------------------------------------
predicate information (identified by operation id):
---------------------------------------------------
   1 - filter(("hiredate"<=to_date(' 1981-04-01 00:00:00', 'syyyy-mm-dd
              hh24:mi:ss') and "hiredate">=to_date(' 1981-01-01 00:00:00',
              'syyyy-mm-dd hh24:mi:ss')))
 
 
21 rows selected.

 

 

 

 

隐式类型转换问题

 

 

implicit and explicit data conversion

 

oracle recommends that you specify explicit conversions, rather than rely on implicit or automatic conversions, for these reasons:

 

·         sql statements are easier to understand when you use explicit datatype conversion functions.

 

·         implicit datatype conversion can have a negative impact on performance, especially if the datatype of a column value is converted to that of a constant rather than the other way around.

 

·         implicit conversion depends on the context in which it occurs and may not work the same way in every case. for example, implicit conversion from a datetime value to a varchar2 value may return an unexpected year depending on the value of the nls_date_format parameter.

 

·         algorithms for implicit conversion are subject to change across software releases and among oracle products. behavior of explicit conversions is more predictable.

 

虽然隐式转换在很多地方自动发生,但是不推荐使用隐式类型转换,oracle官方建议指定显式类型转换,而不要依赖隐式或自动转换,主要有下面一下原因:

 

    使用显式类型转换函数时,sql语句更易于理解。

 

    隐式类型转换可能会对性能产生负面影响,尤其是如果将列值的数据类型转换为常量而不是相反的数据类型转换操作时。

 

    隐式转换取决于发生这种转换的上下文,在不同的情况下,隐式转换的工作方式可能不同。例如,从日期时间值到varchar2值的隐式转换可能会返回错误(意外)的年份,具体取决于nls_date_format参数的值。

 

    隐式转换算法可能会在软件版本之间以及oracle产品之间发生变化。明确转换的行为更容易预测。否则有可能埋下一个大坑。

 

   如果在索引表达式中发生隐式类型转换,则oracle数据库可能不使用索引,因为它是pre-conversion data type.。这可能会对性能产生负面影响。

 

tom kyte的这篇博文on implicit conversions and more,还总结了隐式数据类型转换会带来的一些问题:

 

 

the resulting code typically has logic bombs in it. the code appears to work in certain circumstances but will not work in others.

  •  the resulting code relies on default settings. if someone changes the default settings, the way the code works will be subject to change. (a dba     changing a setting can make your code work entirely differently from the way it does today.)
  •  the resulting code can very well be subject to sql injection bugs.
  •  the resulting code may end up performing numerous unnecessary repeated conversions (negatively affecting performance and consuming many more resources than necessary).
  •  the implicit conversion may be precluding certain access paths from being available to the optimizer, resulting in suboptimal query plans. (in fact, this is exactly what is happening to you!)

    隐式转换可能会阻止某些访问路径无法用于优化器,从而导致查询计划不理想。 (实际上,这正是您数据库当中正在发生的事情!)

  •  implicit conversions may prevent partition elimination.

 

 

    其实上面已经有相关例子介绍,下面介绍一个例子,主要用来说明,隐式类型转换不一定导致执行计划不走索引,只有当隐式转换函数出现在查询条件中的索引字段上,而且左值的类型被隐式转为了右值的类型时才会出现严重性能问题。

 

sql> drop table test;
 
table dropped.
 
sql> create table test
  2  as
  3  select * from dba_objects;
 
table created.
 
sql> create index ix_test_n1 on test(object_id);
 
index created.
 
sql> select count(*) from test where object_id='20';
 
  count(*)
----------
         1
 
sql> select * from table(dbms_xplan.display_cursor);
 
plan_table_output
--------------------------------------------------------------------------------
sql_id  29jmhh43kkrv4, child number 0
-------------------------------------
select count(*) from test where object_id='20'
 
plan hash value: 4037411162
 
--------------------------------------------------------------------------------
| id  | operation         | name       | rows  | bytes | cost (%cpu)| time     |
--------------------------------------------------------------------------------
|   0 | select statement  |            |       |       |     1 (100)|          |
|   1 |  sort aggregate   |            |     1 |    13 |            |          |
 
plan_table_output
--------------------------------------------------------------------------------
|*  2 |   index range scan| ix_test_n1 |    10 |   130 |     1   (0)| 00:00:01 |
--------------------------------------------------------------------------------
predicate information (identified by operation id):
---------------------------------------------------
   2 - access("object_id"=20)
 
note
-----
   - dynamic sampling used for this statement
 
plan_table_output
--------------------------------------------------------------------------------
 
23 rows selected.
 
sql> 

 

 

 

其实sql语句发生了隐式转换,而且转换的地方在字符串’20′上面,转换为数字20。这样的变化没有发生在object_id列上面。其次,这种转换没有发生在左值列上面,没有影响到ix_test_n1的路径。

 

所以以后,如果遇到”隐式转换一定不走索引吗?”或”隐式类型转换一定导致索引失效吗?”这类问题,你都要辩证的来分析,不能一概而论。

 

 

 

下面介绍一个绑定变量发生隐式类型转换的例子:

 

 

 

 

 

sql> create table test
  2  as
  3  select * from dba_objects;             
 
table created.
 
sql> commit;
 
commit complete.
 
sql> create index ix_test_object_name on test(object_name);
 
index created.
 
sql> variables v_object_name nvarchar2(30);
sp2-0734: unknown command beginning "variables ..." - rest of line ignored.
sql> 
sql> variable v_object_name nvarchar2(30);
sql> exec :v_object_name :='i_obj1';
 
pl/sql procedure successfully completed.
 
sql> select count(*) from test where object_name=:v_object_name;
 
  count(*)
----------
         1
 
sql> select * from table(dbms_xplan.display_cursor);
 
plan_table_output
--------------------------------------------------------------------------------
sql_id  ft05prnxtpk9u, child number 0
-------------------------------------
select count(*) from test where object_name=:v_object_name
 
plan hash value: 1950795681
 
---------------------------------------------------------------------------
| id  | operation          | name | rows  | bytes | cost (%cpu)| time     |
---------------------------------------------------------------------------
|   0 | select statement   |      |       |       |   113 (100)|          |
|   1 |  sort aggregate    |      |     1 |    66 |            |          |
 
plan_table_output
--------------------------------------------------------------------------------
|*  2 |   table access full| test |    10 |   660 |   113  (11)| 00:00:01 |
---------------------------------------------------------------------------
predicate information (identified by operation id):
---------------------------------------------------
   2 - filter(sys_op_c2c("object_name")=:v_object_name)
 
note
-----
   - dynamic sampling used for this statement
 
plan_table_output
--------------------------------------------------------------------------------
 
23 rows selected.

 

 

 

这里发生隐式类型转换,是因为隐式类型规则:比较char/varchar2 nchar/nvarchar2时,如果两者字符集不一样,则默认的转换方式是将数据编码从数据库字符集转换为国家字符集 ,而此时是借助内部函数sys_op_c2c实现的

 

 

sys_op_c2c is an internal function which does an implicit conversion of varchar2 to national character set using to_nchar function. thus, the filter completely changes as compared to the filter using normal comparison.

 

 

如何找出存在隐式转换的sql?

 

有些公司可能对发布的sql进行全面审计,能够从源头上杜绝大多数存在隐式类型转换的sql,但是大多数公司可能没有这个能力或资源来实现这个目标,那么,最重要的就是如何找出数据库中存在隐式转换的sql,关于如何找出存在隐式数据类型转换的sql,一般有下面两个sql:

 

 

select

     sql_id,

     plan_hash_value

 from

     v$sql_plan x

 where

     x.filter_predicates like ‘%internal_function%’

 group by

     sql_id,

     plan_hash_value;

 

 

select

     sql_id,

     plan_hash_value

 from

     v$sql_plan x

 where

     x.filter_predicates like ‘%sys_op_c2c%’

 group by

     sql_id,

     plan_hash_value;

 

 

但是需要注意的是,即使执行计划中存在internal_function,也不一定说明sql语句出现了隐式数据类型转换,关于这个问题,参考我的博客oracle数据库中执行计划出现internal_function一定是隐式转换吗?。 所以还必须对找出的相关sql进行仔细甄别、鉴定。

 

 

另外,这篇博客oracle中内部函数sys_op_c2c和隐式类型转换,也值得对隐式类型转换了解不深的同学看看。

 

 

 

 

 

如何避免隐式类型转换呢?

 

1:在数据库设计阶段和写sql期间,尽量遵循一致的原则,避免不必要的数据类型转换。

 

 

   在建模时,要统一字段类型,尤其是和其它表进行关联的相关字段必须保证数据类型一致。这样可以避免不必要的隐式数据类型转换。

 

 

   查询sql中条件与字段类型保持一致,另外,确保绑定变量的数据类型。使其与对应字段的数据类型一致

 

 

2:使用转换函数,进行显示类型转换。

 

 

例如有下面一些常见的类型转换函数:

 

·         to_char:把datenumber转换成字符串;

·         to_date:把numbercharvarchar2转换成date。当用到时间戳时,可以用到to_timestampto_timestamp_tz

·         to_number:  charvarchar2转换成number

 

 

3:创建带有sys_op_c2c的函数索引。

 

 

这种方法比较少用,不过确实也是特殊场景下的一种优化方法。

 

 

 

 

参考资料:

 

https://blogs.oracle.com/oraclemagazine/on-implicit-conversions-and-more

https://docs.oracle.com/cd/e21764_01/apirefs.1111/e12048/cql_elements.htm#cqllr290

https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/data-type-comparison-rules.html#guid-98be3a78-6e33-4181-b5cb-d96fd9dc1694

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐