创建Function
CREATE [OR REPLACE] FUNCTION function_name (arguments)
RETURNS return_datatype
LANGUAGE plpgsql
AS $variable_name$
DECLARE
declaration;
[...] -- variable declaration
BEGIN
< function_body >
[...] -- logic
RETURN { variable_name | value }
END;
$$
参数说明
function_name:Functions名称
[OR REPLACE]:更改当前Functions,可以使用OR REPLACE关键字。它是一个可选参数。
arguments:参数列表。一个Functions可以包含零个或多个参数。
return_datatype:Function的返回值类型,可以是表列类型的基本类型、复合类型或域类型或引用。
function_body:逻辑的可执行部分
示例
Create function get_car_Price(Price_from int, Price_to int)
returns int
language plpgsql
as
$$
Declare
Car_count integer;
Begin
select count(*)
into Car_count
from Car
where Car_price between Price_from and Price_to;
return Car_count;
End;
$$;
说明
SELECT INTO命令将输出提供给Car_count
调用Function
- Select get_car_Price(26000,70000);
- select get_car_Price(Price_from => 26000, Price_to => 70000);
- select get_car_Price(Price_from := 26000, Price_to := 70000);