July 2005
Intermediate to advanced
1032 pages
27h 10m
English
Starting with PostgreSQL version 8.0, you can write polymorphic functions in PL/pgSQL. A polymorphic function is a function with at least one parameter of type ANYELEMENT or ANYARRAY. The types ANYELEMENT and ANYARRAY are called polymorphic types because they can assume different “shapes” at run-time.
Here's a simple polymorphic function that will return the greater of two arguments:
-- ch07.sql
CREATE OR REPLACE FUNCTION max( arg1 ANYELEMENT, arg2 ANYELEMENT )
RETURNS ANYELEMENT AS $$
BEGIN
IF( arg1 > arg2 ) THEN
RETURN( arg1 );
ELSE
RETURN( arg2 );
END IF;
END;
$$ LANGUAGE 'plpgsql';
When you call this function with two INTEGER values, PL/pgSQL treats the function as if you had defined it as
CREATE OR REPLACE FUNCTION ...
Read now
Unlock full access