存储过程

本章我们将讨论存储过程。

创建存储过程

使用 CREATE PROCEDURE 语句创建存储过程,语法如下:

示例数据:

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);

以下示例用于将指定金额从一个账户转账到另一个账户:

create or replace procedure transfer(
   sender int,
   receiver int, 
   amount dec
)
language plpgsql    
as $$
begin
    -- 从转账人账户里扣除金额
    update accounts 
    set balance = balance - amount 
    where id = sender;

    -- 给收款人账号增加金额
    update accounts 
    set balance = balance + amount 
    where id = receiver;

    commit;
end $$;

调用存储过程:

call transfer(1,2,1000);

删除存储过程

删除存储过程的语法:

要查看完整内容,请先登录