此脚本不依赖统计信息。

    在开发过程中,我们应该尽量避免编写标量子查询。我们可以通过分析执行计划,抓出标量子查询语句。同一个 SQL 语句,执行计划中如果有两个或者两个以上的 depth=1 的执行计划就表示 SQL 中出现了标量子查询。以下脚本抓出 Scott 账户下在 SQL*Plus 中运行过的标量子查询语句。

    1. select sql_id, sql_text, module
    2. from v$sql
    3. where parsing_schema_name = 'SCOTT'
    4. and module = 'SQL*Plus'
    5. AND sql_id in
    6. (select sql_id
    7. from (select sql_id,
    8. count(*) over(partition by sql_id, child_number, depth) cnt
    9. from V$SQL_PLAN
    10. where depth = 1
    11. and (object_owner = 'SCOTT' or object_owner is null))
    12. where cnt >= 2);

    我们在 SQL*Plus 中运行如下标量子查询语句。

    1. select dname,
    2. (select max(sal) from emp where deptno = d.deptno) max_sal
    3. from dept d;
    1. DNAME MAX_SAL
    2. -------------- ----------
    3. ACCOUNTING 5000
    4. RESEARCH 3000
    5. SALES 2850
    6. OPERATIONS

    我们利用以上脚本将刚运行过的标量子查询抓出。

    1. select sql_id, sql_text, module
    2. from v$sql
    3. where parsing_schema_name = 'SCOTT'
    4. and module = 'SQL*Plus'
    5. AND sql_id in
    6. (select sql_id
    7. from (select sql_id,
    8. count(*) over(partition by sql_id, child_number, depth) cnt
    9. from V$SQL_PLAN
    10. where depth = 1
    11. and (object_owner = 'SCOTT' or object_owner is null))
    12. where cnt >= 2);
    1. SQL_ID SQL_TEXT MODULE
    2. --------------- ---------------------------------------------- ---------------------
    3. 739fhcu0pbz28 select dname, (select max(sal) from emp where SQL*Plus
    4. deptno = d.deptno) max_sal from dept d