1. 程式人生 > >oracle開發過程中儘量使用繫結變數

oracle開發過程中儘量使用繫結變數

在儲存過程或者java程式使用sql的過程中,儘量使用繫結變數。否則硬解析太多,比較拖效能。

下面查詢只是空格多了幾個。

SQL> select * from ml_1234 where a=          2
  2  ;
 
                                      A
---------------------------------------
 
SQL> select * from ml_1234 where a=      2
  2  ;
 

檢視程式碼解析

 
SQL> select sql_text from v$sqlarea where sql_text like 'select * from ml_1234 %';
 
SQL_TEXT
--------------------------------------------------------------------------------
select * from ml_1234 where a=1
select * from ml_1234
select * from ml_1234 where a=  1
select * from ml_1234 where a=          2
select * from ml_1234 where a=   2
 
SQL> 


如果使用繫結變數,出來就是一條解析sql, 他們可以共用解析,只走軟解析。

SQL> var v1 number
SQL> begin
  2  :v1:=2;
  3  end;
  4  /
 
PL/SQL procedure successfully completed
v1
---------
2
 
SQL> select * from ml_1234 where a=:v1;
 
                                      A
---------------------------------------
v1
---------
2
 
SQL> var v1 number
SQL> begin
  2  :v1:=4;
  3  end;
  4  /
 
PL/SQL procedure successfully completed
v1
---------
4
 
SQL> select * from ml_1234 where a=:v1;
 
                                      A
---------------------------------------
v1
---------
4
 
SQL> select sql_text from v$sqlarea where sql_text like 'select * from ml_1234 %';
 
SQL_TEXT
--------------------------------------------------------------------------------
select * from ml_1234 where a=1
select * from ml_1234
select * from ml_1234 where a=  1
select * from ml_1234 where a=          2
select * from ml_1234 where a=   2
select * from ml_1234 where a=:v1