An example of casting between distinct data types
Suppose you want to define distinct types to represent dollar, yen, and sterling currencies. Any comparison between two currencies must take the exchange rate into account. Thus, you must create cast functions that not only handle the cast from one data type to the other data type but also calculate the exchange rate for the values that you want to compare.
CREATE DISTINCT TYPE dollar AS DOUBLE PRECISION;
CREATE DISTINCT TYPE yen AS DOUBLE PRECISION;
CREATE DISTINCT TYPE sterling AS DOUBLE PRECISION;
CREATE TABLE manufact_price
(
product_desc VARCHAR(20),
us_price dollar,
japan_price yen,
uk_price sterling
);
INSERT INTO manufact_price
VALUES ('baseball', 5.00::DOUBLE PRECISION::dollar,
510.00::DOUBLE PRECISION::yen,
3.50::DOUBLE PRECISION::sterling);
Because a distinct type does not inherit any of the built-in casts available to its source type, each of the preceding INSERT statements requires two casts. For each INSERT statement, the inner cast converts from DECIMAL to DOUBLE PRECISION and the outer cast converts from DOUBLE PRECISION to the correct distinct type (dollar, yen, or sterling).
CREATE FUNCTION dollar_to_yen(d dollar)
RETURN (d::DOUBLE PRECISION * 106)::CHAR(20)::yen;
END FUNCTION;
CREATE FUNCTION sterling_to_dollar(s sterling)
RETURNS dollar
RETURN (s::DOUBLE PRECISION * 1.59)::CHAR(20)::dollar;
END FUNCTION;
CREATE CAST(dollar AS yen WITH dollar_to_yen);
CREATE CAST(sterling AS dollar WITH sterling_to_dollar);
After you register the function as a cast, use it for operations that require conversions between the data types. For the syntax that you use to create a cast function and register it as a cast, see the CREATE FUNCTION and CREATE CAST statements in the HCL OneDB™ Guide to SQL: Syntax.
SELECT * FROM manufact_price
WHERE CAST(us_price AS yen) < japan_price;
SELECT * FROM manufact_price
WHERE us_price::yen < japan_price;
SELECT us_price::yen, japan_price FROM manufact_price
WHERE us_price::yen < japan_price;