How to use an Oracle Associative Array in a SQL query

前端 未结 2 1669
自闭症患者
自闭症患者 2020-12-15 11:47

ODP.Net exposes the ability to pass Associative Arrays as params into an Oracle stored procedure from C#. Its a nice feature unless you are trying to use the data contained

相关标签:
2条回答
  • 2020-12-15 11:58

    I would create a database type like this:

    create type v2t as table of varchar2(30);
    /
    

    And then in the procedure:

    FOR i IN 1..associativeArray.COUNT LOOP
        databaseArray.extend(1);
        databaseArray(i) := associativeArray(i);
    END LOOP;
    
    OPEN refCursor FOR
    SELECT T.*
    FROM   SOME_TABLE T,
           ( SELECT COLUMN_VALUE V
             FROM   TABLE( databaseArray )
           ) T2
    WHERE  T.NAME = T2.V;
    

    (where databaseArray is declared to be of type v2t.)

    0 讨论(0)
  • 2020-12-15 12:01

    You cannot use associative arrays in the SQL scope - they are only usable in the PL/SQL scope.

    One method is to map the associative array to a collection (which can be used in the SQL scope if the collection type has been defined in the SQL scope and not the PL/SQL scope).

    SQL:

    CREATE TYPE VARCHAR2_200_Array_Type AS TABLE OF VARCHAR2(200);
    /
    

    PL/SQL

    DECLARE
      TYPE associativeArrayType IS TABLE OF VARCHAR2(200) INDEX BY PLS_INTEGER;
      i                PLS_INTEGER;
      associativeArray associativeArrayType;
      array            VARCHAR2_200_Array_Type;
      cur              SYS_REFCURSOR;
    BEGIN
      -- Sample data in the (sparse) associative array
      associativeArray(-2) := 'Test 1';
      associativeArray(0)  := 'Test 2';
      associativeArray(7)  := 'Test 3';
    
      -- Initialise the collection
      array := VARCHAR2_200_Array_Type();
    
      -- Loop through the associative array
      i := associativeArray.FIRST;
      WHILE i IS NOT NULL LOOP
        array.EXTEND(1);
        array(array.COUNT) := associativeArray(i);
        i := associativeArray.NEXT(i);
      END LOOP;
    
      -- Use the collection in a query
      OPEN cur FOR
        SELECT *
        FROM   your_table
        WHERE  your_column MEMBER OF array;
    END;
    /
    
    0 讨论(0)
提交回复
热议问题