Inlist的绑定优化(书摘备查)

 -- 建立类型
CREATE OR REPLACE TYPE numtabletype AS TABLE OF NUMBER;

CREATE OR REPLACE TYPE vartabletype AS TABLE OF VARCHAR2 (1000);

 

-- 解析字符串
CREATE OR REPLACE FUNCTION str2numlist (p_string IN VARCHAR2)
   RETURN numtabletype
AS
   v_str    LONG         DEFAULT p_string || ',';
   v_n      NUMBER;
   v_data   numtabletype := numtabletype ();
BEGIN
   LOOP
      v_n := TO_NUMBER (INSTR (v_str, ','));
      EXIT WHEN (NVL (v_n, 0) = 0);
      v_data.EXTEND;
      v_data (v_data.COUNT) := LTRIM (RTRIM (SUBSTR (v_str, 1, v_n - 1)));
      v_str := SUBSTR (v_str, v_n + 1);
   END LOOP;

   RETURN v_data;
END;

 

CREATE OR REPLACE FUNCTION str2varlist (p_string IN VARCHAR2)
   RETURN vartabletype
AS
   v_str    LONG            DEFAULT p_string || ',';
   v_n      VARCHAR2 (2000);
   v_data   vartabletype    := vartabletype ();
BEGIN
   LOOP
      v_n := INSTR (v_str, ',');
      EXIT WHEN (NVL (v_n, 0) = 0);
      v_data.EXTEND;
      v_data (v_data.COUNT) := LTRIM (RTRIM (SUBSTR (v_str, 1, v_n - 1)));
      v_str := SUBSTR (v_str, v_n + 1);
   END LOOP;

   RETURN v_data;
END;

 

-- 绑定查询
SELECT /*+ ordered use_nl(a,u) */
       ID, NAME, nick
  FROM TABLE (str2numlist (:bind0)) a, users u
 WHERE u.ID = a.COLUMN_VALUE;

 

SELECT /*+ leading(a) */
       ID, NAME, nick
  FROM users u
 WHERE ID IN (SELECT *
                FROM TABLE (str2numlist (:bind0)) a);

 

SELECT /*+ index(u ind_users_id) */
       ID, NAME, nick
  FROM users u
 WHERE ID IN (SELECT *
                FROM THE (SELECT CAST (str2numlist (:bind0) AS numtabletype)
                            FROM DUAL)
               WHERE ROWNUM < 1000);

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页