ORACLE中内部函数SYS_OP_C2C和隐式类型转换

 新葡亰计算机网络     |      2020-04-05

什么是SYS_OP_C2C呢?官方的介绍如下:

SQL Server 中什么情况会导致其执行计划从索引查找(Index Seek)变成索引扫描(Index Scan)呢? 下面从几个方面结合上下文具体场景做了下测试、总结、归纳。

 

 

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.

1:隐式转换会导致执行计划从索引查找(Index Seek)变为索引扫描(Index Scan)

 

Implicit Conversion will cause index scan instead of index seek. While implicit conversions occur in SQL Server to allow data evaluations against different data types, they can introduce performance problems for specific data type conversions that result in an index scan occurring during the execution.  Good design practices and code reviews can easily prevent implicit conversion issues from ever occurring in your design or workload.

 

 

简单的来说,SYS_OP_C2C 是一个内部函数,功能是将VARCHAR2的数据类型转换成国家字符集的NVARCHAR2类型,内部通过TO_NCHAR函数实现。

如下示例,AdventureWorks2014数据库的HumanResources.Employee表,由于NationalIDNumber字段类型为NVARCHAR,下面SQL发生了隐式转换,导致其走索引扫描(Index Scan)

 

SELECT NationalIDNumber, LoginID  

FROM HumanResources.Employee  

WHERE NationalIDNumber = 112457891 

 

图片 1

 

我们可以通过两种方式避免SQL做隐式转换:

其实为什么要介绍一下这个内部函数,是因为最近一个同事在优化一个SQL语句时,发现即使创建了相关字段的索引,但是SQL语句的执行计划仍然不走索引,而走全表扫描,个人在分析了后,发现即使这个索引涉及的三个字段的选择率不高,但是也不是不走索引的原因,而是因为隐式转换问题(全局临时表的跟物理表关联的字段数据类型不一致),如果Automatic SQL Tuning - SQL Profiles Tuning Advisor建议创建基于SYS_OP_C2C的函数索引,或者执行计划中有类似“ filter(SYS_OP_C2C(COLUMN).....”这样的信息,那么你应该检查是否出现了隐式类型转换(implicit type conversion)

    1:确保比较的两者具有相同的数据类型。

 

    2:使用强制转换(explicit conversion)方式。

 

我们通过确保比较的两者数据类型相同后,就可以让SQL走索引查找(Index Seek),如下所示

什么是隐式类型转换(implicit type conversion)?

SELECT nationalidnumber,

       loginid

FROM   humanresources.employee

WHERE  nationalidnumber = N'112457891' 

 

图片 2

 

注意:并不是所有的隐式转换都会导致索引查找(Index Seek)变成索引扫描(Index Scan),Implicit Conversions that cause Index Scans 博客里面介绍了那些数据类型之间的隐式转换才会导致索引扫描(Index Scan)。如下图所示,在此不做过多介绍。

如果进行比较的两个值的数据类型不同,则 ORACLE 必须将其中一个值进行类型转换使其能够比较。这就是所谓的隐式类型转换。通常当开发人员将数字存储在字符列时会导致这种问题的产生。ORACLE 在运行时会强制转化其中一个值,(由于固定的规则)在索引字符列使用 to_number。由于添加函数到索引列所以导致索引不被使用。实际上,ORACLE 也只能这么做,类型转换是一个应用程序设计因素。由于转换是在每行都进行的,这会导致性能问题。详见:

图片 3

图片 4

避免隐式转换的一些措施与方法

    1:良好的设计和代码规范(前期)

    2:对发布脚本进行Rreview(中期)

    3:通过脚本查询隐式转换的SQL(后期)

下面是在数据库从执行计划中搜索隐式转换的SQL语句

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DECLARE @dbname SYSNAME 

SET @dbname = QUOTENAME(DB_NAME());

WITH    (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 

SELECT 

   stmt.value('(@StatementText)[1]', 'varchar(max)'), 

   t.value('(ScalarOperator/Identifier/ColumnReference/@Schema)[1]', 'varchar(128)'), 

   t.value('(ScalarOperator/Identifier/ColumnReference/@Table)[1]', 'varchar(128)'), 

   t.value('(ScalarOperator/Identifier/ColumnReference/@Column)[1]', 'varchar(128)'), 

   ic.DATA_TYPE AS ConvertFrom, 

   ic.CHARACTER_MAXIMUM_LENGTH AS ConvertFromLength, 

   t.value('(@DataType)[1]', 'varchar(128)') AS ConvertTo, 

   t.value('(@Length)[1]', 'int') AS ConvertToLength, 

   query_plan 

FROM sys.dm_exec_cached_plans AS cp 

CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 

CROSS APPLY query_plan.nodes('/ShowPlan) AS batch(stmt) 

CROSS APPLY stmt.nodes('.//Convert[@Implicit="1"]') AS n(t) 

JOIN INFORMATION_SCHEMA.COLUMNS AS ic 

   ON QUOTENAME(ic.TABLE_SCHEMA) = t.value('(ScalarOperator/Identifier/ColumnReference/@Schema)[1]', 'varchar(128)') 

   AND QUOTENAME(ic.TABLE_NAME) = t.value('(ScalarOperator/Identifier/ColumnReference/@Table)[1]', 'varchar(128)') 

   AND ic.COLUMN_NAME = t.value('(ScalarOperator/Identifier/ColumnReference/@Column)[1]', 'varchar(128)') 

WHERE t.exist('ScalarOperator/Identifier/ColumnReference[@Database=sql:variable("@dbname")][@Schema!="[sys]"]') = 1

 

2:非SARG谓词会导致执行计划从索引查找(Index Seek)变为索引扫描(Index Scan)

 

    SARG(Searchable Arguments)又叫查询参数, 它的定义:用于限制搜索的一个操作,因为它通常是指一个特定的匹配,一个值的范围内的匹配或者两个以上条件的AND连接。不满足SARG形式的语句最典型的情况就是包括非操作符的语句,如:NOT、!=、<>;、!<;、!>;NOT EXISTS、NOT IN、NOT LIKE等,另外还有像在谓词使用函数、谓词进行运算等。

 

2.1:索引字段使用函数会导致索引扫描(Index Scan)

SELECT nationalidnumber,

       loginid

FROM   humanresources.employee

WHERE  SUBSTRING(nationalidnumber,1,3) = '112'

图片 5

 

2.2索引字段进行运算会导致索引扫描(Index Scan)

    对索引字段字段进行运算会导致执行计划从索引查找(Index Seek)变成索引扫描(Index Scan):

    SELECT  * FROM Person.Person WHERE  BusinessEntityID + 10 < 260

图片 6

 

一般要尽量避免这种情况出现,如果可以的话,尽量对SQL进行逻辑转换(如下所示)。虽然这个例子看起来很简单,但是在实际中,还是见过许多这样的案例,就像很多人知道抽烟有害健康,但是就是戒不掉!很多人可能了解这个,但是在实际操作中还是一直会犯这个错误。道理就是如此!

SELECT  * FROM Person.Person WHERE  BusinessEntityID  < 250

图片 7

 

2.3 LIKE模糊查询回导致索引扫描(Index Scan)

    Like语句是否属于SARG取决于所使用的通配符的类型, LIKE 'Condition%' 就属于SARG、LIKE ’%Condition'就属于非SARG谓词操作

SELECT  * FROM Person.Person WHERE LastName LIKE 'Ma%'

图片 8

SELECT  * FROM Person.Person WHERE LastName LIKE '%Ma%'

图片 9

 

3:SQL查询返回数据页(Pages)达到了临界点(Tipping Point)会导致索引扫描(Index Scan)或表扫描(Table Scan)

 

What is the tipping point?

It's the point where the number of rows returned is "no longer selective enough". SQL Server chooses NOT to use the nonclustered index to look up the corresponding data rows and instead performs a table scan.

    关于临界点(Tipping Point),我们下面先不纠结概念了,先从一个鲜活的例子开始吧:

SET NOCOUNT ON;

DROP TABLE TEST

CREATE TABLE TEST (OBJECT_ID  INT, NAME VARCHAR(8));

 

CREATE INDEX PK_TEST ON TEST(OBJECT_ID)

DECLARE @Index INT =1;

 

WHILE @Index <= 10000

BEGIN

    INSERT INTO TEST

    SELECT @Index, 'kerry';

   

    SET @Index = @Index +1;

END

UPDATE STATISTICS  TEST WITH FULLSCAN;

 

SELECT * FROM TEST WHERE OBJECT_ID= 1

如上所示,当我们查询OBJECT_ID=1的数据时,优化器使用索引查找(Index Seek)

图片 10

上面OBJECT_ID=1的数据只有一条,如果OBJECT_ID=1的数据达到全表总数据量的20%会怎么样? 我们可以手工更新2001条数据。此时SQL的执行计划变成全表扫描(Table Scan)了。

UPDATE TEST SET OBJECT_ID =1 WHERE OBJECT_ID<=2000;

 

UPDATE STATISTICS  TEST WITH FULLSCAN;

 

SELECT * FROM TEST WHERE OBJECT_ID= 1

图片 11

图片 12

临界点决定了SQL Server是使用书签查找还是全表/索引扫描。这也意味着临界点只与非覆盖、非聚集索引有关(重点)。

Why is the tipping point interesting?

  • It shows that narrow (non-covering) nonclustered indexes have fewer uses than often expected (just because a query has a column in the WHERE clause doesn't mean that SQL Server's going to use that index)

  • It happens at a point that's typically MUCH earlier than expected… and, in fact, sometimes this is a VERY bad thing!

  • Only nonclustered indexes that do not cover a query have a tipping point. Covering indexes don't have this same issue (which further proves why they're so important for performance tuning)

  • You might find larger tables/queries performing table scans when in fact, it might be better to use a nonclustered index. How do you know, how do you test, how do you hint and/or force… and, is that a good thing?

 

4:统计信息缺失或不正确会导致索引扫描(Index Scan)

     统计信息缺失或不正确,很容易导致索引查找(Index Seek)变成索引扫描(Index Scan)。 这个倒是很容易理解,但是构造这样的案例比较难,一时没有想到,在此略过。

 

5:谓词不是联合索引的第一列会导致索引扫描(Index Scan)

SELECT * INTO Sales.SalesOrderDetail_Tmp FROM Sales.SalesOrderDetail;

 

CREATE INDEX PK_SalesOrderDetail_Tmp ON Sales.SalesOrderDetail_Tmp(SalesOrderID, SalesOrderDetailID);

 

UPDATE STATISTICS  Sales.SalesOrderDetail_Tmp WITH FULLSCAN;

下面这个SQL语句得到的结果是一致的,但是第二个SQL语句由于谓词不是联合索引第一列,导致索引扫描

SELECT * FROM Sales.SalesOrderDetail_Tmp

WHERE SalesOrderID=43659 AND SalesOrderDetailID<10

图片 13

SELECT * FROM Sales.SalesOrderDetail_Tmp WHERE SalesOrderDetailID<10

图片 14

 

 

参考资料:

Document 232243.1 ORA-01722 ORA-01847 ORA-01839 or ORA-01858 From Queries with Dependent Predicates

 

 

官方文档SYS_OP_C2C Causing Full Table/Index Scans (文档 ID 732666.1)中有介绍:

 

APPLIES TO:

 

Oracle Database - Enterprise Edition - Version 10.1.0.2 to 12.1.0.1 [Release 10.1 to 12.1]

Information in this document applies to any platform.

This problem can occur on any platform.

 

SYMPTOMS

 

1) You are executing a query using bind variables.

2) The binding occurs via an application (eg. .NET, J2EE ) using a "string" variable to bind.

3) The query is incorrectly performing a full table/index scan instead of an unique/range index scan. 

4) When looking at advanced explain plan, sqltxplain or 10053 trace, you notice that the "Predicate Information" shows is doing a "filter(SYS_OP_C2C)".

 

e.g select * from table(dbms_xplan.display_cursor(&sql_id,null,'ADVANCED'));

 

Predicate Information (identified by operation id):


1 - filter(SYS_OP_C2C("COL1")=:B1)            <=== filter operation occurring

 

 

CAUSE

 

上一篇:SQLServer删除数据 下一篇:没有了