如何为函数参数指定泛型类型

use*_*074 5 postgresql

是否可以在Postgresql中定义一个采用泛型类型参数的函数?因此,例如,如果我想定义一个函数,其中参数可以是数字或字符变化:

CREATE OR REPLACE FUNCTION toStr(col ??Generic Type??)
  RETURNS character varying AS
$BODY$
select 
case when pg_typeof(col) = 'character varying'::regtype then col::'character varying'
case when pg_typeof(col) = 'numeric'::regtype then to_char(col::numeric, '999')
  else 'Unsupported type'
$BODY$
Run Code Online (Sandbox Code Playgroud)

所以,如果这是可能的,那么我的通用类型会怎样?是?

Joa*_*son 7

您可以使用接受任何数据类型的anyelement 类型;

CREATE OR REPLACE FUNCTION toStr(col anyelement)
  RETURNS character varying 
AS $$
select 
case when pg_typeof(col) = 'character varying'::regtype then (col::character varying)
     when pg_typeof(col) = 'numeric'::regtype then to_char(col::numeric, '999')
  else 'Unsupported type' end
$$
LANGUAGE sql;
Run Code Online (Sandbox Code Playgroud)

一个SQLfiddle显示它在行动.