如何在對in操作使用變數繫結(轉)

zhouwf0726發表於2019-05-25

如何在對in操作使用變數繫結

  大家都知道在sql語句中變數繫結的重大意義,甚至有高人指出:一個應用想要它變的很糟糙的話,只要不使用變數繫結就可以了。這話的確不假。這時可能有人就會問:我該繫結的都繫結了,可是我實在無法想到好的方法在in操作符中使用變數繫結。下面的方法可以解決這個疑問。

  我們知道in操作符接受兩種list, 一個是由一個個item組成的list, 另一個是由另一個表中選出的list。第一種方式由於值個數不一定,變數繫結具有一定的困難。於是我們思路就集中到準備將一個字串傳入到sql語句中,然後使用一個方法將字串parse成一個table, 再傳回in operator:

首先我們來建立方法,及由此方法返回的table型別:
rudolf@test9i> create or replace type numTableType as table
2 of number
3 /

Type created.

rudolf@test9i> create or replace function str2numList( p_string in varchar2 ) return
2 numTableType
3 as
4 v_str long default p_string || ',';
5 v_n number;
6 v_data numTableType := numTableType();
7 begin
8 loop
9 v_n := to_number(instr( v_str, ',' ));
10 exit when (nvl(v_n,0) = 0);
11 v_data.extend;
12 v_data( v_data.count ) := ltrim(rtrim(substr(v_str,1,v_n-1)));
13 v_str := substr( v_str, v_n+1 );
14 end loop;
15 return v_data;
16 end;
17 /

Function created.

  我們把下列語句:
select object_name from t where object_id in ( xx,xxx,xxx,...);
  改為:
select object_name from t
  where object_id in
( select * from THE ( select cast( str2numList(:variable ) as numtableType ) from dual )
      );

現在我們來看看是否達到了我們的目的:
  rudolf@test9i> var STR varchar2(3000)

rudolf@test9i> exec :STR := '5770,1810,4481'

PL/SQL procedure successfully completed.

rudolf@test9i> alter session set events= '10046 trace name context forever, level 4'
2 /

Session altered.

rudolf@test9i> select object_id,object_name from t where object_id in (
2 select * from THE ( select cast( str2numList(:STR ) as numtableType ) from
3 dual ) )
4
rudolf@test9i> /

OBJECT_ID OBJECT_NAME
---------- ------------------------------
1810 ALL_ALL_TABLES
4481 AGGXMLINPUTTYPE
5770 ALL_APPLY

檢查dump檔案,我們看到(注意星號的行):

PARSING IN CURSOR #1 len=146 dep=0 uid=81 oct=3 lid=81 tim=1036636837633718 hv=2833917919 ad='529b9f48'
select object_id,object_name from t where object_id in (
select * from THE ( select cast( str2numList(:STR ) as numtableType ) from
dual ) )
END OF STMT
PARSE #1:c=0,e=655,p=0,cr=0,cu=0,mis=1,r=0,dep=0,og=0,tim=1036636837633701
BINDS #1:         *****
bind 0: dty=1 mxl=2000(200) mal=00 scl=00 pre=00 oacflg=03 oacfl2=10 size=2000 offset=0
bfp=406402fc bln=2000 avl=14 flg=05
value="5770,1810,4481"
EXEC #1:c=0,e=245,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=4,tim=1036636837645450 FETCH #1:c=20000,e=16739,p=0,cr=52,cu=0,mis=0,r=1,dep=0,og=4,tim=1036636837662283 FETCH #1:c=0,e=4644,p=0,cr=0,cu=0,mis=0,r=2,dep=0,og=4,tim=1036636837667979

看得出,它的確使用了變數繫結。


/******************the other article********************/

使用繫結變數帶來的好處不用多說,但是遇到SQL條件中條件值不固定的這類SQL在普通方式下就不能使用繫結變數,看到Tom網站上提供了一種可行的辦法。

網上有不少的地方也提到了這種方法,那就是,先定義一個表型別,將個數不定的引數轉換成這種表型別,再將查詢結果傳給IN子句,這樣就可以實現了SQL語句中的繫結變數方式。
例如:
Select * From 病人費用記錄 Where NO IN(Select * From Table(Cast(zlTools.f_Str2List ('A01,A02,A03') as zlTools. t_StrList)));
Select * From 病人費用記錄 Where NO IN(Select * From The(Select Cast(zlTools.f_Str2List ('A01,A02,A03') as zlTools. t_StrList) From Dual));
Select A.* From 病人費用記錄 A,Table(Cast(zlTools.f_Str2List ('A01,A02,A03') as zlTools. t_StrList)) B Where A.NO=B.Column_Value;

Oracle提供了一個包dbms_utility.comma_to_table可以將引數列表轉換為一個型別表,但是由於結果是通過引數傳出的,無法用於應用程式的SQL語句中。

於是,我們仍然選擇通過建立SQL表型別和相關函式來實現,Type:t_StrList, t_NumList, 函式:f_Str2List, f_Num2List,如下:

Create Or Replace type zltools.t_StrList as table of varchar2(4000)
/
Create Or Replace Function zltools.f_Str2List(Str_In In Varchar2) Return zltools.t_StrList As
v_Str Long Default Str_In || ',';
v_Index Number;
v_List zltools.t_StrList := zltools.t_StrList();
--功能:將由逗號分隔的不帶引號的字元序列轉換為資料表
--引數:Str_In如:G0000123,G0000124,G0000125...
Begin
Loop
v_Index := Instr(v_Str, ',');
Exit When(Nvl(v_Index, 0) = 0);
v_List.Extend;
v_List(v_List.Count) := Trim(Substr(v_Str, 1, v_Index - 1));
v_Str := Substr(v_Str, v_Index + 1);
End Loop;
Return v_List;
End;
/
Create Or Replace type zltools.t_NumList as table of number
/
Create Or Replace Function zltools.f_Num2List(Str_In In Varchar2) Return zltools.t_NumList As
v_Str Long Default Str_In || ',';
v_Index Number;
v_List zltools.t_NumList := zltools.t_NumList();
--功能:將由逗號分隔的數字序列轉換為資料表
--引數:Str_In如:73265,73266,73267....
Begin
Loop
v_Index := Instr(v_Str, ',');
Exit When(Nvl(v_Index, 0) = 0);
v_List.Extend;
v_List(v_List.Count) := To_Number(Trim(Substr(v_Str, 1, v_Index - 1)));
v_Str := Substr(v_Str, v_Index + 1);
End Loop;
Return v_List;
End;
/


但是這種方法有一個問題:
如果使用者使用CBO,使用這種方式的SQL語句,不加處理的話一般(要根據具體SQL分析)會錯誤的使用Hash連線來產生執行計劃,不能正確使用索引從而引發效能問題,
因為Type Table不具備統計資訊,在計算成本時,Oracle始終認為它有8168行,在基於成本的優化器模式下,多表連線時一般就會選擇Hash連線,一般比使用索引的巢狀連線效率差。

目前,已知的解決辦法有兩種:
http://www.cnoug.org/viewthread.php?tid=1533&highlight=DROP%2B%2BCONSTRAINT%2Bindex
1. 對構造表的返回記錄集加RowNum條件,通過子查詢的實體化檢視來改變執行計劃,例如:
select * from table(Cast(zlTools.f_Str2List (v_str) as zlTools.t_StrList)) where rownum<5
2. 在SQL中加入優化器提示,例如:/*+ rule*/,或者/*+ ordered use_nl(t)*/,或者/*+ index(t ind_object_id)*/

第1種方式,需要對rownum的條件賦值,如果條件值採用動態的值,那麼就達不到使用繫結變數的效果,如果採用固定值,有兩種方案:
一種是使用一個固定的極限值,例如:99999,另一種是使用繫結變數。
試驗結果見文末,這兩種方式產生的執行計劃採用了Hash連線,執行計劃比不使用RowNum實體化檢視更差。

第2種方式,如果使用指定巢狀連線提示或指定索引提示則需要對每個SQL針對性處理,需要分析具體的SQL。所以,一般情況建議在SQL中使用/*+ rule*/提示來固定執行計劃。


--0.準備
--先建立表型別及轉換函式: t_StrList,f_Str2List和t_NumList,f_Num2List
SQL> alter session set optimizer_mode=all_rows;
Session altered
SQL> var v_str varchar2(4000);
SQL> exec :v_str :='H0000005,H0000006,H0000007';

PL/SQL 過程已成功完成。


--1.當型別表不使用Rownum實體化檢視時,錯誤地採用了Hash連線的執行計劃,產生了6575塊邏輯讀+6909塊物理讀
SQL> Select a.No, a.結算方式, Nvl(b.性質, 1) As 性質, a.金額, a.摘要, a.結算號碼
2 From (Select b.No, Decode(a.記錄性質, 3, a.結算方式, Null) As 結算方式, a.摘要, a.結算號碼, Sum
(1 * a.衝預交) As 金額
3 From 病人預交記錄 a,
4 (Select Distinct No, 結帳id
5 From 病人費用記錄
6 Where 記錄性質 = 1 And No In (
7 Select * From Table(Cast(f_Str2List(:v_str) as t_StrList))
8 ) And 記錄狀態 In (1, 3)) b
9 Where a.結帳id = b.結帳id And a.記錄性質 In (1, 11, 3) And Nvl(a.衝預交, 0) <> 0
10 Group By b.No, Decode(a.記錄性質, 3, a.結算方式, Null), a.摘要, a.結算號碼) a, 結算方式 b
11 Where a.結算方式 = b.名稱(+);


執行計劃
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=23 Card=1 Bytes=100)
1 0 NESTED LOOPS (OUTER) (Cost=23 Card=1 Bytes=100)
2 1 VIEW (Cost=22 Card=1 Bytes=75)
3 2 SORT (GROUP BY) (Cost=22 Card=1 Bytes=94)
4 3 VIEW (Cost=21 Card=1 Bytes=94)
5 4 SORT (UNIQUE) (Cost=21 Card=1 Bytes=149)
6 5 TABLE ACCESS (BY INDEX ROWID) OF '病人預交記錄' (Cost=1 Card=1 Bytes=102)
7 6 NESTED LOOPS (Cost=19 Card=1 Bytes=149)
8 7 HASH JOIN (SEMI) (Cost=17 Card=4 Bytes=188)
9 8 INDEX (FAST FULL SCAN) OF '病人費用記錄_UQ_NO' (UNIQUE) (Cost=4 Card=399 Bytes=17955)
10 8 COLLECTION ITERATOR (PICKLER FETCH) OF 'f_Str2List'
11 7 INDEX (RANGE SCAN) OF '病人預交記錄_IX_結帳ID' (NON-UNIQUE)
12 1 TABLE ACCESS (BY INDEX ROWID) OF '結算方式' (Cost=1 Card=1 Bytes=25)
13 12 INDEX (UNIQUE SCAN) OF '結算方式_UQ_名稱' (UNIQUE)

統計資訊
----------------------------------------------------------
0 recursive calls
0 db block gets
6575 consistent gets
6909 physical reads
0 redo size
720 bytes sent via SQL*Net to client
372 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
2 sorts (memory)
0 sorts (disk)
3 rows processed

--2.當型別表的查詢條件中Rownum使用固定值時,正確地採用了巢狀連線的執行計劃,僅僅產生了29塊邏輯讀
SQL> Select a.No, a.結算方式, Nvl(b.性質, 1) As 性質, a.金額, a.摘要, a.結算號碼
2 From (Select b.No, Decode(a.記錄性質, 3, a.結算方式, Null) As 結算方式, a.摘要, a.結算號碼, Sum
(1 * a.衝預交) As 金額
3 From 病人預交記錄 a,
4 (Select Distinct No, 結帳id
5 From 病人費用記錄
6 Where 記錄性質 = 1 And No In (
7 Select * From Table(Cast(f_Str2List(:v_str) as t_StrList)) Where Rownum<4
8 ) And 記錄狀態 In (1, 3)) b
9 Where a.結帳id = b.結帳id And a.記錄性質 In (1, 11, 3) And Nvl(a.衝預交, 0) <> 0
10 Group By b.No, Decode(a.記錄性質, 3, a.結算方式, Null), a.摘要, a.結算號碼) a, 結算方式 b
11 Where a.結算方式 = b.名稱(+);


執行計劃
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=23 Card=4 Bytes=400)
1 0 NESTED LOOPS (OUTER) (Cost=23 Card=4 Bytes=400)
2 1 VIEW (Cost=21 Card=4 Bytes=300)
3 2 SORT (GROUP BY) (Cost=21 Card=4 Bytes=376)
4 3 VIEW (Cost=20 Card=4 Bytes=376)
5 4 SORT (UNIQUE) (Cost=20 Card=4 Bytes=8596)
6 5 TABLE ACCESS (BY INDEX ROWID) OF '病人預交記錄' (Cost=1 Card=1 Bytes=102)
7 6 NESTED LOOPS (Cost=17 Card=4 Bytes=8596)
8 7 NESTED LOOPS (Cost=13 Card=12 Bytes=24564)
9 8 VIEW OF 'VW_NSO_1' (Cost=11 Card=3 Bytes=6006)
10 9 COUNT (STOPKEY)
11 10 COLLECTION ITERATOR (PICKLER FETCH) OF 'f_Str2List'
12 8 INLIST ITERATOR
13 12 INDEX (RANGE SCAN) OF '病人費用記錄_UQ_NO' (UNIQUE) (Cost=1 Card=4 Bytes=180)
14 7 INDEX (RANGE SCAN) OF '病人預交記錄_IX_結帳ID' (NON-UNIQUE)
15 1 TABLE ACCESS (BY INDEX ROWID) OF '結算方式' (Cost=1 Card=1 Bytes=25)
16 15 INDEX (UNIQUE SCAN) OF '結算方式_UQ_名稱' (UNIQUE)

統計資訊
----------------------------------------------------------
0 recursive calls
0 db block gets
29 consistent gets
0 physical reads
0 redo size
720 bytes sent via SQL*Net to client
372 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
2 sorts (memory)
0 sorts (disk)
3 rows processed

--3.當型別表的查詢條件中Rownum使用變數時,執行計劃雖然有變化,但是仍然認為型別表返回的記錄集數為8168,
-- 錯誤地採用了Hash連線的執行計劃,產生了374369塊邏輯讀和11192塊物理讀
SQL> var v_count number;
SQL> exec :v_count:=4;

PL/SQL 過程已成功完成。

SQL> Select a.No, a.結算方式, Nvl(b.性質, 1) As 性質, a.金額, a.摘要, a.結算號碼
2 From (Select b.No, Decode(a.記錄性質, 3, a.結算方式, Null) As 結算方式, a.摘要, a.結算號碼, Sum
(1 * a.衝預交) As 金額
3 From 病人預交記錄 a,
4 (Select Distinct No, 結帳id
5 From 病人費用記錄
6 Where 記錄性質 = 1 And No In (
7 Select * From Table(Cast(f_Str2List(:v_str) as t_StrList)) Where Rownum<:v_count>8 ) And 記錄狀態 In (1, 3)) b
9 Where a.結帳id = b.結帳id And a.記錄性質 In (1, 11, 3) And Nvl(a.衝預交, 0) <> 0
10 Group By b.No, Decode(a.記錄性質, 3, a.結算方式, Null), a.摘要, a.結算號碼) a, 結算方式 b
11 Where a.結算方式 = b.名稱(+);


執行計劃
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=16306 Card=10945 Bytes=1094500)
1 0 HASH JOIN (OUTER) (Cost=16306 Card=10945 Bytes=1094500)
2 1 VIEW (Cost=16264 Card=10945 Bytes=820875)
3 2 SORT (GROUP BY) (Cost=16264 Card=10945 Bytes=1028830)
4 3 VIEW (Cost=16148 Card=10945 Bytes=1028830)
5 4 SORT (UNIQUE) (Cost=16148 Card=10945 Bytes=23520805)
6 5 HASH JOIN (Cost=238 Card=10945 Bytes=23520805)
7 6 TABLE ACCESS (BY INDEX ROWID) OF '病人預交記錄' (Cost=1 Card=1 Bytes=102)
8 7 NESTED LOOPS (Cost=164 Card=134 Bytes=19698)
9 8 INDEX (FAST FULL SCAN) OF '病人費用記錄_UQ_NO' (UNIQUE) (Cost=4 Card=399 Bytes=17955)
10 8 INDEX (RANGE SCAN) OF '病人預交記錄_IX_結帳ID' (NON-UNIQUE)
11 6 VIEW OF 'VW_NSO_1' (Cost=11 Card=8168 Bytes=16352336)
12 11 COUNT (STOPKEY)
13 12 COLLECTION ITERATOR (PICKLER FETCH) OF 'f_Str2List'
14 1 TABLE ACCESS (FULL) OF '結算方式' (Cost=2 Card=82 Bytes=2050)

統計資訊
----------------------------------------------------------
28 recursive calls
0 db block gets
374369 consistent gets
11192 physical reads
0 redo size
720 bytes sent via SQL*Net to client
372 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
2 sorts (memory)
0 sorts (disk)
3 rows processed

--4.當型別表的查詢條件中Rownum使用一個固定的極限值時(例如:99999),情況與使用變數一樣遭,錯誤地採用了Hash連線的執行計劃,產生了374354塊邏輯讀和10756塊物理讀
SQL> Select a.No, a.結算方式, Nvl(b.性質, 1) As 性質, a.金額, a.摘要, a.結算號碼
2 From (Select b.No, Decode(a.記錄性質, 3, a.結算方式, Null) As 結算方式, a.摘要, a.結算號碼, Sum
(1 * a.衝預交) As 金額
3 From 病人預交記錄 a,
4 (Select Distinct No, 結帳id
5 From 病人費用記錄
6 Where 記錄性質 = 1 And No In (
7 Select * From Table(Cast(f_Str2List(:v_str) as t_StrList)) Where Rownum<99999
8 ) And 記錄狀態 In (1, 3)) b
9 Where a.結帳id = b.結帳id And a.記錄性質 In (1, 11, 3) And Nvl(a.衝預交, 0) <> 0
10 Group By b.No, Decode(a.記錄性質, 3, a.結算方式, Null), a.摘要, a.結算號碼) a, 結算方式 b
11 Where a.結算方式 = b.名稱(+);


執行計劃
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=16306 Card=10945 Bytes=1094500)
1 0 HASH JOIN (OUTER) (Cost=16306 Card=10945 Bytes=1094500)
2 1 VIEW (Cost=16264 Card=10945 Bytes=820875)
3 2 SORT (GROUP BY) (Cost=16264 Card=10945 Bytes=1028830)
4 3 VIEW (Cost=16148 Card=10945 Bytes=1028830)
5 4 SORT (UNIQUE) (Cost=16148 Card=10945 Bytes=23520805)
6 5 HASH JOIN (Cost=238 Card=10945 Bytes=23520805)
7 6 TABLE ACCESS (BY INDEX ROWID) OF '病人預交記錄' (Cost=1 Card=1 Bytes=102)
8 7 NESTED LOOPS (Cost=164 Card=134 Bytes=19698)
9 8 INDEX (FAST FULL SCAN) OF '病人費用記錄_UQ_NO' (UNIQUE) (Cost=4 Card=399 Bytes=17955)
10 8 INDEX (RANGE SCAN) OF '病人預交記錄_IX_結帳ID' (NON-UNIQUE)
11 6 VIEW OF 'VW_NSO_1' (Cost=11 Card=8168 Bytes=16352336)
12 11 COUNT (STOPKEY)
13 12 COLLECTION ITERATOR (PICKLER FETCH) OF 'f_Str2List'
14 1 TABLE ACCESS (FULL) OF '結算方式' (Cost=2 Card=82 Bytes=2050)


統計資訊
----------------------------------------------------------
0 recursive calls
0 db block gets
374354 consistent gets
10756 physical reads
0 redo size
720 bytes sent via SQL*Net to client
372 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
2 sorts (memory)
0 sorts (disk)
3 rows processed

--5.強制使用基於規則的優化器模式
SQL> Select /*+ rule*/ a.No, a.結算方式, Nvl(b.性質, 1) As 性質, a.金額, a.摘要, a.結算號碼
2 From (Select b.No, Decode(a.記錄性質, 3, a.結算方式, Null) As 結算方式, a.摘要, a.結算號碼, Sum
(1 * a.衝預交) As 金額
3 From 病人預交記錄 a,
4 (Select Distinct No, 結帳id
5 From 病人費用記錄
6 Where 記錄性質 = 1 And No In (
7 Select * From Table(Cast(f_Str2List(:v_str) as t_StrList))
8 ) And 記錄狀態 In (1, 3)) b
9 Where a.結帳id = b.結帳id And a.記錄性質 In (1, 11, 3) And Nvl(a.衝預交, 0) <> 0
10 Group By b.No, Decode(a.記錄性質, 3, a.結算方式, Null), a.摘要, a.結算號碼) a, 結算方式 b
11 Where a.結算方式 = b.名稱(+);


執行計劃
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=HINT: RULE
1 0 NESTED LOOPS (OUTER)
2 1 VIEW
3 2 SORT (GROUP BY)
4 3 VIEW
5 4 SORT (UNIQUE)
6 5 TABLE ACCESS (BY INDEX ROWID) OF '病人預交記錄'
7 6 NESTED LOOPS
8 7 NESTED LOOPS
9 8 COLLECTION ITERATOR (PICKLER FETCH) OF 'f_Str2List'
10 8 INDEX (RANGE SCAN) OF '病人費用記錄_UQ_NO' (UNIQUE)
11 7 INDEX (RANGE SCAN) OF '病人預交記錄_IX_結帳ID' (NON-UNIQUE)
12 1 TABLE ACCESS (BY INDEX ROWID) OF '結算方式'
13 12 INDEX (UNIQUE SCAN) OF '結算方式_UQ_名稱' (UNIQUE)


統計資訊
----------------------------------------------------------
0 recursive calls
0 db block gets
25 consistent gets
0 physical reads
0 redo size
720 bytes sent via SQL*Net to client
372 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
2 sorts (memory)
0 sorts (disk)
3 rows processed

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/756652/viewspace-242174/,如需轉載,請註明出處,否則將追究法律責任。

相關文章