Thursday, January 7, 2016

Build IN Clause dynamically and use it in SELECT statement


CREATE OR REPLACE TYPE xx_string_tbl_typ AS TABLE OF VARCHAR2(4000);

CREATE OR REPLACE FUNCTION xx_build_dynamic_in_clause( p_in_clause_strg IN VARCHAR2)
   RETURN xx_string_tbl_typ
AS
   xx_string_tbl   xx_string_tbl_typ := xx_string_tbl_typ();
   l_in_clause     VARCHAR2(4000) :=    p_in_clause_strg || ','; 
-- length can be increase till 32767
   i                                            NUMBER;
BEGIN
   LOOP
      i                                         :=
         INSTR(l_in_clause
             , ',');
      EXIT WHEN NVL(i, 0) = 0;
      xx_string_tbl.EXTEND;
      xx_string_tbl( xx_string_tbl.LAST)        :=
         TRIM(SUBSTR(l_in_clause
                   , 1
                   , i - 1));
      l_in_clause                               :=
         SUBSTR(l_in_clause
              , i + 1);
   END LOOP;

   RETURN xx_string_tbl;
END;
/
--- Test Script to test the Function
SELECT *
  FROM mtl_system_items_b
 WHERE organization_id = &organization_id
   AND inventory_item_id IN (SELECT * FROM TABLE( xx_build_dynamic_in_clause( '&1,&2,&3')))

-- Another method by using PIPELINED function

CREATE OR REPLACE FUNCTION xx_build_dynamic_in_clause( p_in_clause_strg IN VARCHAR2)
   RETURN xx_string_tbl_typ
   PIPELINED
AS
l_in_clause  VARCHAR2(4000):=    p_in_clause_strg || ',';                            -- length can be increase till 32767
   i  NUMBER;
BEGIN
   LOOP
      i                                         :=
         INSTR(l_in_clause
             , ',');
      EXIT WHEN NVL(i, 0) = 0;
      PIPE ROW (TRIM(SUBSTR(l_in_clause
                          , 1
                          , i - 1)));
      l_in_clause                               :=
         SUBSTR(l_in_clause
              , i + 1);
   END LOOP;

   RETURN;
END;
/

--- Test Script to test the Function
SELECT *
  FROM mtl_system_items_b
 WHERE organization_id = &organization_id
   AND inventory_item_id IN (SELECT * FROM TABLE( xx_build_dynamic_in_clause( '&1,&2,&3')))

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.