SQL Server具有一项功能,通过该功能,您可以使用func / proc名称的变量名称来调用函数或存储过程。玩具示例:
declare @name sysname;
declare @method int = 1;
set @name = IIF(@method = 1, N'Newton', N'Taylor')
declare @sqrt float;
exec @sqrt = @name 42
根据@method的值,这将称为Newton或Taylor。使用此功能,可以在T-SQL中实现策略或命令OOP模式。在我工作的地方,我们仅将其用于此目的。
现在我正在学习Postgresql,我想知道如何在pgplsql中做类似的事情。任何提示表示赞赏!
如果所有调用的函数都返回相同数据类型的单个值并采用相同数据类型的单个参数,那么您也可以在Postgres中使用动态SQL来实现:
create or replace function evaluate(p_input integer, p_method text)
returns float
as
$$
declare
l_result float;
begin
execute 'select '||p_method||'($1)'
using p_input
into l_result;
return l_result;
end;
$$
language plpgsql;
select evaluate(42, 'sqrt');
返回6.48074069840786select evaluate(1, 'exp');
返回2.718281828459045这也适用于多个参数:
create or replace function evaluate(p_arg_1 integer, p_arg_2 text, p_method text)
returns float
as
$$
declare
l_result float;
begin
execute 'select '||p_method||'($1, $2)'
using p_arg_1, p_arg_2
into l_result;
return l_result;
end;
$$
language plpgsql;
真好!这种方法可以使用多个arg吗?
@ user1443098:只要所有调用的函数都接受多个参数,是的。
非常适合策略模式。我要买它