Oracle PL/SQL之WITH查询

[转自] http://blog.csdn.net/t0nsha/article/details/6730855


为什么要用WITH?

1. 如果需要在一段复杂查询里多次应用同一个查询,用WITH可实现代码重用;

2. WITH查询类似将查询结果保留到用户临时表里,在大的复杂查询中可以减少IO,有一定的性能优化作用。

 

WITH查询有何限制与特性?

1. 如果当前schema下有与WITH查询别名相同的表,查询中WITH查询生成的表优先;

2. 只能用于select 语句;

3. WITH可包含一个或多个查询;

4. WITH查询可被其它查询或WITH查询引用。

 

示例:

  1. duzz$scott@orcl>select * from dept;  
  2.   
  3.     DEPTNO DNAME           LOC  
  4. ---------- --------------- ----------  
  5.         10 ACCOUNTING      NEW YORK  
  6.         20 RESEARCH        DALLAS  
  7.         30 SALES           CHICAGO  
  8.         40 OPERATIONS      BOSTON  
  9.   
  10. Elapsed: 00:00:00.00  
  11. duzz$scott@orcl>with dept as (select 1 a from dual) select * from dept;  
  12.   
  13.          A  
  14. ----------  
  15.          1  
  16.   
  17. Elapsed: 00:00:00.00  
  18. duzz$scott@orcl>with dept as (select 1 a from dual) delete from dept where a=1;  
  19. with dept as (select 1 a from dual) delete from dept where a=1  
  20.                                     *  
  21. ERROR at line 1:  
  22. ORA-00928: missing SELECT keyword  
  23.   
  24.   
  25. Elapsed: 00:00:00.01  
  26. duzz$scott@orcl>with wt1 as (select 1 a, 2 b from dual), wt2 as (select 1 c,3 d from dual) select * from wt1,wt2 where wt1.a=wt2.c;  
  27.   
  28.          A          B          C          D  
  29. ---------- ---------- ---------- ----------  
  30.          1          2          1          3  
  31.   
  32. Elapsed: 00:00:00.00  
  33. duzz$scott@orcl>with wt1 as (select 10 a, 2 b from dual), wt2 as (select deptno,loc from dept,wt1 where deptno=a) select loc from wt2;  
  34.   
  35. LOC  
  36. ---------------------------------------  
  37. NEW YORK  
  38.   
  39. Elapsed: 00:00:00.00  
  40. duzz$scott@orcl>  

posted @ 2015-02-27 10:35  Pekkle  阅读(460)  评论(0编辑  收藏  举报