Oracle中的关联数组作为参数

Associative array in Oracle as Parameter

我有类似的东西:

TYPE MyType IS TABLE OF VARCHAR2(10) INDEX BY VARCHAR2(10);

如何在类似

的函数中使用它
function TestFunction
(
 Input    in   MyType 
) return number;

作为参数?

类似于TestFunction(MyType('Value1','Value2'));

不起作用,因为我需要一个键 -> 值定义,例如

TestFunction(MyType('key1': 'value1', 'key2': 'value2'));

如何在 Oracle 中将关联数组作为参数传递?

这是一个简单的方法:

SQL> set serveroutput on
SQL> declare
  2      TYPE MyType IS TABLE OF VARCHAR2(10) INDEX BY VARCHAR2(10);
  3      myVar MyType;
  4      function TestFunction
  5      (
  6       Input    in   MyType
  7      ) return number is
  8      begin
  9          return Input.count;
 10      end;
 11
 12  begin
 13      myVar(1) := 'one';
 14      myVar(2) := 'two';
 15      myVar('three') := 'THREE';
 16      dbms_output.put_line(TestFunction(myVar));
 17  end;
 18  /
3

PL/SQL procedure successfully completed.

Oracle 18c介绍Qualified Expressions:

Qualified expressions improve program clarity and developer productivity by providing the ability to declare and define a complex value in a compact form where the value is needed.

A qualified expression combines expression elements to create values of a RECORD type or associative array type.

Qualified expressions use an explicit type indication to provide the type of the qualified item.

DECLARE
    TYPE MyType IS TABLE OF VARCHAR2(10) INDEX BY VARCHAR2(10);
    
    FUNCTION TestFunction(Input IN MyType) RETURN NUMBER
    IS
    BEGIN
        RETURN Input.Count;
    END;
BEGIN
    DBMS_OUTPUT.put_line(TestFunction(MyType('Ind1' => 1, 'Ind2' => 2)));
END;
/
-- output:
-- 2

正在从集合中创建类型 (varray) 和直接 SELECT

CREATE OR REPLACE TYPE MyType is varray(10) of integer;
/

SELECT *
FROM MyType(1,2,3);
-- Output:
COLUMN_VALUE
===========
1
2
3

或作为函数的默认参数:

CREATE OR REPLACE FUNCTION MyFunc(Input IN MyType DEFAULT MyType(1,2,3)) 
RETURN NUMBER
IS
BEGIN
   RETURN Input.Count;
END;
/

SELECT MyFunc FROM dual;
-- Output:
MYFUNC
======
3

db<>fiddle demo