温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Porting strategy pattern from SQL Server to Postgresql
postgresql

其他 - 将策略模式从SQL Server移植到Postgresql

发布于 2020-03-27 10:47:56

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中做类似的事情。任何提示表示赞赏!

查看更多

查看更多

提问者
user1443098
被浏览
153
a_horse_with_no_name 2019-07-03 22:50

如果所有调用的函数都返回相同数据类型的单个值并采用相同数据类型的单个参数,那么您也可以在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.48074069840786
  • select 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;