• postgresql存储过程基本语法


    create table accounts(
    id serial primary key,
    name varchar(50) not null,
    account numeric
    );

    insert into accounts values
    (1,‘Tom’,‘9000’),
    (2,‘Jerry’,‘9000’);

    select * from accounts;

    创建存储过程(真正的存储过程procedure)
    存储过程和函数的区别:

    1. 存储过程标识符:procedure
      函数标识符:function
    2. 存储过程无需return返回值,函数必须有return返回值,
    3. 存储过程可以使用事物,函数中无法使用事物,

    创建存储过程语法:
    create or replace procedure 存储过程名(param_list)
    language plpgsql
    as d e c l a r e 变量名 t y p e [ d e f a u l t v a l u e ] ; b e g i n s q l s t a t e m e n t ; c o m m i t ; e n d ; declare 变量名 type [default value]; begin sql_statement; commit; end; declare变量名type[defaultvalue];beginsqlstatement;commit;end;; – 分号可要可不要

    举例:
    create or replace procedure transfer(id1 int,id2 int,num numeric)
    language plpgsql
    as b e g i n u p d a t e a c c o u n t s s e t a c c o u n t = a c c o u n t − n u m w h e r e i d = i d 1 ; u p d a t e a c c o u n t s s e t a c c o u n t = a c c o u n t + n u m w h e r e i d = i d 2 ; c o m m i t ; − − 提交事务 e n d ; begin update accounts set account=account-num where id = id1; update accounts set account=account+num where id = id2; commit; --提交事务 end; beginupdateaccountssetaccount=accountnumwhereid=id1;updateaccountssetaccount=account+numwhereid=id2;commit;提交事务end;

    或:

    create or replace procedure transfer(int,int,numeric)
    language plpgsql
    as KaTeX parse error: Can't use function '$' in math mode at position 56: …ccount=account-$̲3 where id = $1…

    调用存储过程:
    call transfer(1,2,1000);

    accounts之前数据:
    id name account
    1 Tom 9000
    2 Jerry 9000

    调用存储过程之后的数据:
    id name account
    1 Tom 8000
    2 Jerry 10000

    好了,我是Lee,一枚数据开发,不定期更新一下博客,希望一直这样下去,有东西写。

  • 相关阅读:
    天猫店铺介绍,影响天猫店铺转让价格的六个因素
    手把手带你写嵌入式物联网的第一个项目
    Express框架---中间件
    QLineEdit 类(行编辑器)
    一篇理解网络分层原理
    JAVA-JDK镜像下载地址
    Python数据分析与机器学习42-Python库分析科比生涯数据
    同行评审的度量与分析
    springboot中药知识分享网站毕业设计源码201818
    快速上手Django(六) -Django之Django drf 序列化器Serializer类
  • 原文地址:https://blog.csdn.net/chenzuoli/article/details/126773261