oracle执行每次执行查询都会先判断sga中是否存在该查询语句解析后的缓存,如果不存在则解析该查询语句并存储在sga中,如果存在则直接执行。同样逻辑的sql语句即时仅仅注释不一样oracle也会认为是两个不同的sql语句,如

 
  
  1. select * from tableName; 
  2. select /*注释*/ * from tableName; 

虽然这两个查询返回结果一样,但是oracle认为这是两个不同的查询,执行的时候会分别解析。

-----------分割线----------------------

利用绑定变量能够提高查询效率。测试如下:

  1. 创建测试表
 
  
  1. create table tb_user(id number,username varchar2(10)); 
  2. alter table tb_user add constraint pk_user_id primary key (id); 
插入测试数据
 
  
  1. begin 
  2.     for i in 1..10000 
  3.         loop 
  4.             insert into tb_user values(i,'wjm'||i); 
  5.         end loop; 
  6. end
用非绑定变量方式查询一万次
 
  
  1. alter system flush shared_pool; --清空共享池
  2.  
  3.  
  4. declare 
  5.   type cursorType is ref cursor
  6.   ct_test cursorType; 
  7.   rt_rowType tb_user%rowtype; 
  8. begin  
  9.     for i in 1..1000 
  10.         loop 
  11.             open ct_test for 'select * from tb_user where id='||i;--非绑定变量,拼接字符串 
  12.             fetch ct_test into rt_rowType; 
  13.             close ct_test; 
  14.         end loop; 
  15. end
结果 非绑定变量方式查询一万次所花费的时间 绑定变量方式查询一万次
 
  
  1. alter system flush shared_pool;--清空共享池 
  2. declare 
  3.   type cursorType is ref cursor
  4.   ct_test cursorType; 
  5.   rt_rowType tb_user%rowtype; 
  6. begin  
  7.     for i in 1..1000 
  8.         loop 
  9.             open ct_test for 'select * from tb_user where id=:x' using i;--绑定变量 
  10.             fetch ct_test into rt_rowType; 
  11.             close ct_test; 
  12.         end loop; 
  13. end
 结果

绑定变量方式查询一万次花费时间

通过两次查询所花费的时间可以看到绑定变量方式编写sql能有效提高查询效率。