All Products
Search
Document Center

PolarDB:Collection type constructors

Last Updated:Mar 27, 2024

A collection type constructor is a system-defined function that has the same name as a collection type. The function returns a collection of that type. Only variable-length arrays and nested tables allow you to use constructors to initialize collection variables.

Syntax

type_name ( [ value [, value ]... ] )

If you do not specify any parameter, the constructor returns an empty collection. Otherwise, the constructor returns a collection that contains the specified elements. Because the maximum length of a variable-length array is limited, the number of values that the constructor contains cannot exceed the maximum length. Otherwise, the database identifies the constructor as a regular function.

Examples

DECLARE
  TYPE varray_type IS VARRAY(2) OF INT;
  v varray_type := varray_type(1, 2, 3);
BEGIN
END;

Sample result:

ERROR:  function varray_type(integer, integer, integer) does not exist
LINE 1: varray_type(1, 2, 3)
        ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
QUERY:  varray_type(1, 2, 3)
CONTEXT:  PL/SQL function inline_code_block line 4 during statement block local variable initialization

The following example shows how to set the initial value to an empty value or to contain a specific element:

DECLARE
  TYPE Friend IS VARRAY(4) OF VARCHAR(10);
  good_friend Friend := Friend(); -- Set the initial value to an empty value.
 
  PROCEDURE print_friend (heading VARCHAR) - The local procedure.
  IS
  BEGIN
    RAISE NOTICE '%', heading;
 
    IF good_friend.COUNT = 0 THEN
      RAISE NOTICE 'Empty';
    ELSE 
      FOR i IN 1..2 LOOP
        RAISE NOTICE '%.%', i, good_friend(i);
      END LOOP;
    END IF;
 
    RAISE NOTICE '---'; 
  END;
 
BEGIN
  print_friend('Friend:');
  good_friend := Friend('Zhang', 'Wu'); -- Set the initial value to a specified value.
  print_friend('Friend:');
END;

Sample result:

NOTICE:  Friend:
NOTICE:  Empty
NOTICE:  ---
NOTICE:  Friend:
NOTICE:  1.Zhang
NOTICE:  2.Wu
NOTICE:  ---
DO