gpt4 book ai didi

sql - 检查输入参数并引发异常

转载 作者:行者123 更新时间:2023-11-29 14:27:51 25 4
gpt4 key购买 nike

最近我一直在使用一些显然有效的函数。我想添加一些功能,例如:“如果函数输入参数是一个字符串,它会引发异常,说些什么”。我该怎么做?

 /*
PLpgSQL function which behaves to aggregate the MIN(col)
*/
CREATE OR REPLACE FUNCTION searchMinimumValue (real,real) RETURNS real AS $$
DECLARE
BEGIN
IF $1 IS NULL OR $1 >= $2 THEN
RETURN $2;
ELSE
RETURN $1;
END IF;
END;
$$ LANGUAGE plpgsql;

/*
Function which given the minimum value returned from the previous function,
adds the Laplacian noise.
Our upper bound is computed by doubling the epsilon value and then adding our minimum value found by the previous function.
The returned value from the function below will be the Laplace distribution value added to the output from the previous function.
*/
CREATE OR REPLACE FUNCTION addLaplacianNoiseMinimum(real) RETURNS real AS $$
DECLARE
epsilon real := 1.2;
sensivity real := (epsilon * 2) + $1;
laplaceDistribution real;
BEGIN
laplaceDistribution := sensivity / (epsilon);
RETURN $1 + laplaceDistribution;
END;
$$ LANGUAGE plpgsql;

CREATE AGGREGATE minimumLaplaceValue (real)
(
sfunc = searchMinimumValue,
stype = real,
finalfunc = addLaplacianNoiseMinimum
);

正如我之前所说,我想输入如下内容:如果 $1 不是数字,则引发异常“错误类型的输入参数”

最佳答案

我认为你不能用 Postgres 做到这一点——或者你不能在没有一些不必要的副作用的情况下做到这一点。

Postgres 是严格的类型系统 - 所以所有类型的工作都应该由 Postgres 完成。

但是您可以为某些类型的参数集重载函数:

CREATE OR REPLACE FUNCTION public.f1(numeric)
RETURNS numeric
LANGUAGE plpgsql
AS $function$
begin
return $1;
end;
$function$

CREATE OR REPLACE FUNCTION public.f1(text)
RETURNS text
LANGUAGE plpgsql
AS $function$
begin
raise exception 'only numeric type is supported';
end;
$function$

postgres=# select f1(10);
+----+
| f1 |
+----+
| 10 |
+----+
(1 row)

postgres=# select f1('ahoj');
ERROR: only numeric type is supported
CONTEXT: PL/pgSQL function f1(text) line 3 at RAISE

但我强烈不建议使用这种模式。重载是狂野的枪 - 可以是好 friend 也可以是坏 friend ,并且应该只在需要时使用它并且可以做一些工作 - 它不应该仅仅用于引发异常。这是 postgres 类型系统的工作——它做得更好(尽管有不同的,也许在第一眼看来是奇怪的错误消息)。

关于sql - 检查输入参数并引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881185/

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