多态类型

最近更新时间: 2025-02-18 16:02:00

  • 复制
    复制成功
postgres=# CREATE OR REPLACE FUNCTION f_any(a_arg anyelement) RETURNS VOID AS
postgres-# $$
postgres$# BEGIN
postgres$#     RAISE NOTICE '%',a_arg;
postgres$# END;
postgres$# $$
postgres-# LANGUAGE PLPGSQL;
CREATE FUNCTION
postgres=#
postgres=# SELECT f_any(1::integer);
NOTICE:  1
 f_any
-------
(1 行记录)
postgres=# SELECT f_any('TDSQL PG'::TEXT);
NOTICE:  TDSQL PG
 f_any
-------
(1 行记录)
postgres=# SELECT f_any(ROW(1,'TDSQL PG')::public.t_rec);
NOTICE:  (1,TDSQL PG)
 f_any
-------
(1 行记录)
postgres=# SELECT f_any(ARRAY[1,2]::INTEGER[]);
NOTICE:  {1,2}
 f_any
-------
(1 行记录)
postgres=# SELECT f_any(ARRAY[[1,2],[3,4],[5,6]]::INTEGER[][][]);
NOTICE:  {{1,2},{3,4},{5,6}}
 f_any
-------
(1 行记录)
#注意多态类型参数函数调用时最好直接声明参数类型,否则有可能出错
postgres=# CREATE OR REPLACE FUNCTION f_any_array(a_arg anyarray) RETURNS VOID AS
postgres-# $$
postgres$# BEGIN
postgres$#     RAISE NOTICE '%',a_arg;
postgres$# END;
postgres$# $$
postgres-# LANGUAGE PLPGSQL;
CREATE FUNCTION
postgres=#
postgres=# SELECT f_any_array(ARRAY['TDSQL PG','pgxz']::TEXT[]);
NOTICE:  {TDSQL PG,pgxz}
 f_any_array
-------------
(1 行记录)
postgres=# SELECT f_any_array(ARRAY[ARRAY['TDSQL PG','pgxz'],ARRAY['TDSQL PG','Tencent']]::TEXT[][]);
NOTICE:  {{TDSQL PG,pgxz},{TDSQL PG,Tencent}}
 f_any_array
-------------
(1 行记录)

注意:

Anyelement参数如果写成数组,其意义就跟anyarray参数一致,所以 f_any(a_arg anyelement)与f_any(a_arg anyarray)在调用f_any(ARRAY[1,2])时就会出现函数不是唯一化的错误(ERROR: function f_any(…) is not unique)提示。