The typed collection variable
A typed collection variable provides an exact description of the collection. This declaration specifies the data type of the collection (SET, MULTISET, or LIST) and the element type for the collection variable.
- Any built-in data type (such as INTEGER, CHAR, BOOLEAN, and FLOAT) except BYTE, TEXT, SERIAL, or SERIAL8.
- Collection data types, such as SET and LIST, to create a nested collection
- Unnamed row types (named row types are not valid)
- Opaque data types
client collection set(char(20) not null) set_var;
A named row type is not valid as the element type of a collection variable. However, you can specify an element type of unnamed row type, whose fields match those fields of the named row type.
CREATE ROW TYPE myrow
(
a int,
b float
);
CREATE TABLE mytable
(
col1 int8,
col2 set(myrow not null)
);
EXEC SQL BEGIN DECLARE SECTION;
client collection set(row(a int, b float) not null)
my_collection;
EXEC SQL END DECLARE SECTION;
You can declare a typed collection variable whose element type is different from that of the collection column as long as the two data types are compatible. If the database server is able to convert between the two element types, it automatically performs this conversion when it returns the fetched collection.
CREATE TABLE tab1 (col1 SET(INTEGER NOT NULL))
EXEC SQL BEGIN DECLARE SECTION;
client collection set(float not null) set_float;
client collection set(integer not null) set_int;
EXEC SQL END DECLARE SECTION;
EXEC SQL declare cur1 cursor for select * from tab1;
EXEC SQL open cur1;
EXEC SQL fetch cur1 into:set_float;
EXEC SQL fetch cur1 into :set_int;
When it executes the first FETCH statement, the client program automatically converts the integer elements in the column to the float values in the set_float host variable. The program only generates a type-mismatch error if you change the host variable after the first fetch. In the preceding code fragment, the second FETCH statement generates a type-mismatch error because the initial fetch has already defined the element type as float.
- When you insert into a derived table ( needs to know what the type is)
- When you update an element in a derived table ( needs to know what the type is)
- When you want the server to perform a cast. (The client sends the type information to the database server, which attempts to perform the requested cast operation. If it is not possible, the database server returns an error.)
EXEC SQL BEGIN DECLARE SECTION;
client collection multiset(integer not null) mset1, mset2;
EXEC SQL END DECLARE SECTION;
You cannot declare collection variables for different collection types in a single declaration line.