gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:27:52 24 4
gpt4 key购买 nike

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

CREATE OR REPLACE FUNCTION public.icase(
cond1 boolean,
res1 anyelement,
conddefault anyelement)
RETURNS anyelement AS
' SELECT CASE WHEN $1 THEN $2 ELSE $3 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)datenumeric<,则可以调用此方法int 类型。

最佳答案

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

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

CREATE OR REPLACE FUNCTION public.icase1(cond1 boolean,
res1 numeric, conddefault numeric)
RETURNS numeric AS $$
SELECT CASE WHEN $1 THEN $2 ELSE $3 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)

关于sql - 如何在 Postgres 9.1+ 函数中使用混合的 int 和数字参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30330555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com