PL/pgSQL 函数参数模式:IN、OUT、INOUT

在本教程中,您将了解的功能参数模式,包括: in , out ,和 inout 。

摘要:在本教程中,您将了解的功能参数模式,包括: in , out ,和 inout 。

PL/pgSQL 参数模式介绍

参数模式决定了参数的行为。PL / pgSQL的支持三种参数模式: in , out ,和 inout 。 in 如果您未明确指定,则参数默认采用模式。

下表说明了三种参数模式:

在 出去 进出
默认的 明确指定 明确指定
将值传递给函数 从函数返回一个值 将值传递给函数并返回更新的值。
in 参数就像常量一样 out 参数就像未初始化的变量 inout 参数就像一个初始化变量
无法赋值 必须赋值 应该赋值

输入模式

以下函数根据电影的 id 查找电影并返回电影的标题:

create or replace function find_film_by_id(p_film_id int)
returns varchar
language plpgsql
as $$
declare
   film_title film.title%type;
begin
  -- find film title by id
  select title 
  into film_title
  from film
  where film_id = p_film_id;

  if not found then
     raise 'Film with id % not found', p_film_id;
  end if;

  return title;

end;$$

因为我们没有为 p_film_id 参数指定模式,所以 in 默认采用模式。

输出模式

该 out 参数被定义为参数列表的一部分,并返回作为结果的一部分。

这些 out 参数在需要返回多个值的函数中非常有用。

请注意,PostgreSQL out 从 8.1 版本开始支持这些参数。

要定义 out 参数,请在参数名称之前明确使用 out 关键字,如下所示:

out parameter_name type

以下示例定义了 get_film_stat 具有三个 out 参数的函数:

create or replace function get_film_stat(
    out min_len int,
    out max_len int,
    out avg_len numeric) 
language plpgsql
as $$
begin

  select min(length),
         max(length),
         avg(length)::numeric(5,1)
  into min_len, max_len, avg_len
  from film;

end;$$

在 get_film_stat 功能,我们选择最小值,最大值,和平均薄膜长度的从 film 使用表 min , max 和 avg 聚集函数,并将结果指定给相应的 out 参数。

以下语句调用该 get_film_stat 函数:

select get_film_stat();

该函数的输出是一条记录。要将输出分隔为列,请使用以下语句:

select * from get_film_stat();

输入输出模式

的 inout 模式是组合 in 和 out 模式。

这意味着调用者可以将参数传递给函数。该函数更改参数并返回更新后的值。

以下 swap 函数接受两个整数及其值:

create or replace function swap(
    inout x int,
    inout y int
) 
language plpgsql    
as $$
begin
   select x,y into y,x;
end; $$;

以下语句调用该 swap() 函数:

select * from swap(10,20);

概括

  • PL / pgSQL的支持三种参数模式: in , out ,和 intout 。默认情况下,参数采用 in 模式。
  • in 如果要将值传递给函数,请使用该模式。
  • out 如果要从函数返回值,请使用该模式。
  • inout 当您想传入初始值,更新函数中的值,并将更新后的值返回时,请使用该模式。