PostgreSQL存储过程介绍

PG的从11版本支持存储过程,存储过程支持事物,所以在存储过程中可以commit,rollback事物,从oracle迁移存储过程也得到了更好的支持。

语法如下:

create [or replace] procedure procedure_name(parameter_list)
language plpgsql
as $$
declare
-- variable declaration
begin
-- stored procedure body
end; $$

可以看到和创建函数语法类似,但是参数只有in和inout类型,没有out类型。因为存储过程和函数不一样,它不返回值,所以不能使用return返回数据,但是可以只写return来表示停止过程。

下面看一个存储过程的例子

1.新建表accounts,插入两条数据
drop table if exists accounts;

create table accounts (
    id int generated by default as identity,
    name varchar(100) not null,
    balance dec(15,2) not null,
    primary key(id)
);

insert into accounts(name,balance)
values('Bob',10000);

insert into accounts(name,balance)
values('Alice',10000);
2.创建一个存储过程并调用
create or replace procedure transfer(
   sender int,
   receiver int, 
   amount dec
)
language plpgsql    
as $$
begin
    -- id等于sender的减去amount
    update accounts 
    set balance = balance - amount 
    where id = sender;

    -- id等于amount的增加amount
    update accounts 
    set balance = balance + amount 
    where id = receiver;

    commit;
end;$$
--调用存储过程的语法如下:
all stored_procedure_name(argument_list);
--调用过程,id=1的行balance减去100,id=2的行balance加1000
call transfer(1,2,1000);
--查看结果
select * from accounts;

你可能感兴趣的:(#,postgreSQL,数据库)