zoukankan      html  css  js  c++  java
  • 存储过程入门

    我们常用的操作数据库语言SQL语句在执行的时候需要要先编译,然后执行,而存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给定参数(如果该存储过程带有参数)来调用执行它。

    一个存储过程是一个可编程的函数,它在数据库中创建并保存。它可以有SQL语句和一些特殊的控制结构组成。当希望在不同的应用程序或平台上执行相同的函数,或者封装特定功能时,存储过程是非常有用的。数据库中的存储过程可以看做是对编程中面向对象方法的模拟。它允许控制数据的访问方式。

    简单来说就是存储过程就是将若干条sql语句封装起来,编译好放在mysql服务器中,需要时调用即可

    存储过程的创建语法

    create procedure procedureName()
    begin
        //sql语句
    end
    

    存储过程是可以编程的,意味着可以使用变量、表达式、控制结构,来完成复杂的功能

    1.在存储过程中,使用declare声明变量,其格式为:declare 变量名 变量类型 [default 默认值]

    例如:

    create procedure p1()
    begin
        declare age int default 18;
        declare height int default 180;
        select concat('年龄',age,'身高是',height);
    end

     2.存储过程中,变量可以使用sql语句进行合法的运算,如+、-、*、/

      运算结果赋值给变量: set 变量名 := expression(表达式)

    create procedure p2()
    begin
        declare age int default 18;
        set age := age + 20;
        select concat('20年后年龄是',age);
    end

     3.控制结构,与我们平常见到的if、else差不多

    create procedure p3()
    begin
    	declare age int default 18;
    	if age > 18 then
    		select '已成年';
    	else 
    		select '未成年';
    	end if;
    end
    

    4.循环结构(while和repeat)

    //循环结构
    create procedure p4()
    begin
        declare num int default 0;
        declare total int default 0;
    
        while num <=100 do
            set total := total + num;
            set num := num + 1;
        end while;
    
        select total;
    end$

    create procedure p5()
    begin
        declare i int default 0;
        declare total int default 0;
    
        repeat
        set i := i + 1;
        set total := total + i;
        until i >= 100 end repeat;
    
        select total;
    end$

    5.case结构(类似java的switch)

    create procedure p6()
    begin
        declare pos int default 0;
    
        set pos := floor(5*rand());
    
        case pos
        when 1 then select '还在飞';
        when 2 then select '掉海里了';
        when 3 then select '在小岛上';
        else select '我不知道';
        end case;
    end$
  • 相关阅读:
    canvas,制作炫酷的时钟和倒计时
    【bzoj2142】【礼物】拓展Lucas定理+孙子定理
    【hdu3652】数位dp(浅尝ACM-A)
    【bzoj4152】【The Captain】最短路(堆优化)(浅尝ACM-B)
    【bzoj2190】【仪仗队】欧拉函数+线性筛(浅尝ACM-J)
    【bzoj1087】【互不侵犯King】状压dp裸题(浅尝ACM-D)
    【bzoj1566】【管道取珠】竟然是dp题(浅尝ACM-E)
    【bzoj2957】【楼房重建】另类的线段树(浅尝ACM-H)
    【codevs1907】【方格取数3】二分图最大带权独立集
    二分图变种之最小路径覆盖、最小点覆盖集【poj3041】【poj2060】
  • 原文地址:https://www.cnblogs.com/lzxl/p/4117804.html
Copyright © 2011-2022 走看看