多态类型

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

  • 复制
    复制成功
postgres=# CREATE OR REPLACE PROCEDURE f_any(a_arg anyelement) AS
$$
BEGIN
    RAISE NOTICE '%',a_arg;
END;
$$
LANGUAGE PLPGSQL;
CREATE PROCEDURE
postgres=# CALL f_any(1);
NOTICE:  1
CALL
postgres=# CALL f_any('Tbase'::varchar);
NOTICE:  Tbase
CALL
postgres=#
postgres=# SELECT f_any('TBase'::TEXT);
NOTICE:  TBase
 f_any
-------
(1 行记录)
postgres=# CALL f_any(ROW(1,'TBase')::public.t);    
NOTICE:  (1,TBase)
CALL
postgres=#
postgres=# CALL f_any(ARRAY[1,2]::INTEGER[]);
NOTICE:  {1,2}
CALL
postgres=#
postgres=# CALL  f_any(ARRAY[[1,2],[3,4],[5,6]]::INTEGER[][][]);
NOTICE:  {{1,2},{3,4},{5,6}}
CALL
postgres=#
#注意多态类型参数调用时最好直接声明参数类型,否则有可能出错
postgres=# CREATE OR REPLACE PROCEDURE f_any(a_arg anyarray) AS
$$
BEGIN
    RAISE NOTICE '%',a_arg;
END;
$$
LANGUAGE PLPGSQL;
CREATE PROCEDURE
postgres=# call f_any(ARRAY['TBase','pgxz']::TEXT[]);        
ERROR:  procedure f_any(text[]) is not unique
LINE 1: call f_any(ARRAY['TBase','pgxz']::TEXT[]);
             ^
HINT:  Could not choose a best candidate procedure. You might need to add explicit type casts.
postgres=#

注意:

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