扫码一下
查看教程更方便
postgresql函数,也称为存储过程,允许您在数据库中的单个函数中执行通常需要多次查询和往返的操作。函数允许重用数据库,因为其他应用程序可以直接与您的存储过程交互,而不是中间层或重复代码。
可以使用您选择的语言(如 sql 、pl/pgsql、c、python 等)创建函数。
创建函数的基本语法如下 -
create [or replace] function function_name (arguments)
returns return_datatype as $variable_name$
declare
declaration;
[...]
begin
< function_body >
[...]
return { variable_name | value }
end; language plpgsql;
说明
以下示例说明了创建和调用独立函数。此函数返回 company 表中的记录总数。我们使用的company表,其中包含以下记录
id | name | age | address | salary
---- ------- ----- ----------- --------
1 | paul | 32 | california| 20000
2 | allen | 25 | texas | 15000
3 | teddy | 23 | norway | 20000
4 | mark | 25 | rich-mond | 65000
5 | david | 27 | texas | 85000
6 | kim | 22 | south-hall| 45000
7 | james | 24 | houston | 10000
(7 rows)
函数 totalrecords() 定义如下
create or replace function totalrecords ()
returns integer as $total$
declare
total integer;
begin
select count(*) into total from company;
return total;
end;
$total$ language plpgsql;
执行上述查询时,结果如下
jiyik_db=# create function
现在,让我们执行对该函数的调用并检查 company 表中的记录
jiyik_db=# select totalrecords();
执行上述查询时,结果如下
totalrecords
--------------
7
(1 row)