Download Creating User-Defined Routines and User-Defined Data

Transcript
Choosing the Cast Mechanism
3.
Register the cast with the CREATE CAST statement.
Use the WITH clause of the CREATE CAST statement to specify the
cast function. To invoke a cast function, the function must reside in
the current database. However, the cast function does not need to
exist when you register the cast.
Example of a Cast Function
For example, suppose you want to compare values of two opaque data types,
int_type and float_type. Both types have an external LVARCHAR format that
you can use as an intermediate type for converting from one to the other. The
CREATE FUNCTION statement in Figure 7-1 creates and registers an SPL
function, int_to_float(), as an argument. It casts the int_type input value to
an LVARCHAR, and then casts the LVARCHAR result to float_type and returns
the float_type result.
CREATE FUNCTION int_to_float(int_arg int_type)
RETURNS float_type
RETURN CAST(CAST(int_arg AS LVARCHAR) AS float_type);
END FUNCTION;
Figure 7-1
An SPL Function as a
Cast Function from
int_type to float_type
The int_to_float() function uses a nested cast and the support functions of the
int_type and float_type opaque types to obtain the return value, as follows:
1.
The int_to_float() function converts the int_type argument to
LVARCHAR with the inner cast:
CAST(int_arg AS LVARCHAR)
The output support function of the int_type opaque data type serves
as the cast function for this inner cast. This output support function
must be defined as part of the definition of the int_type opaque data
type; it converts the internal format of int_type to its external
(LVARCHAR) format.
Creating User-Defined Casts 7-9