如何在 Postgres 9.1+ 函数中使用混合的 int 和数字参数

How to use mixed int and numeric arguments in a Postgres 9.1+ function

我正在寻找一种创建 icase() 函数的方法,该函数适用于任何第二个和第三个参数兼容的数据类型。
我在 Postgres 9.4 中试过:

CREATE OR REPLACE FUNCTION public.icase(
    cond1 boolean,
    res1 anyelement,
    conddefault anyelement)
  RETURNS anyelement AS
' SELECT CASE WHEN  THEN  ELSE  END; '
  LANGUAGE sql IMMUTABLE;

但是:

select icase( true, 1.0, 0 )

导致错误:

ERROR:  function icase(boolean, numeric, integer) does not exist
LINE 9: select icase( true, 1.0, 0 )
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

如何在 9.1+ 中解决此问题,以便第二个和第三个参数可以是 int 或数字?

如果第二个和第三个参数都是textchar(n)datenumericint类型,则可以调用此方法

此时多态类型是严格的 - 在其他情况下,PostgreSQL 尝试将常量转换为最常见的类型,但多态类型缺少此步骤 - 因此在这种情况下,当您描述问题时,您有显式转换或者你不应该使用多态类型。 B 计划结束函数重载

CREATE OR REPLACE FUNCTION public.icase1(cond1 boolean,
                                         res1 integer, conddefault integer)
RETURNS integer AS $$
SELECT CASE WHEN  THEN  ELSE  END;
$$ LANGUAGE sql;

CREATE OR REPLACE FUNCTION public.icase1(cond1 boolean,
                                         res1 numeric, conddefault numeric)
RETURNS numeric AS $$
SELECT CASE WHEN  THEN  ELSE  END;
$$ LANGUAGE sql;

那么您的代码将按预期工作:

postgres=> select icase1(true, 1.0, 0);
 icase1 
--------
    1.0
(1 row)

postgres=> select icase1(true, 1.0, 1.0);
 icase1 
--------
    1.0
(1 row)

postgres=> select icase1(true, 1, 0);
 icase1 
--------
      1
(1 row)