创建存储过程和函数

#1.创建数据表
create table sch(
    id int(10) primary key not null unique,
    name varchar(50) not null,
    glass varchar(50) not null
);
#插入数据
insert into sch values(1,'xiaoming','glass1'),(2,'xiaojun','glass2');
#查看创建的表格
DESC sch;
#查看表中的内容
SELECT * FROM sch;

#2.创建一个存储函数来统计表sch中的记录数
create function count_sch()
returns int
return (select count(*) from sch);
#查看
select count_sch() as count_sch;
#创建的存储函数名称为count_sch,通过select count_sch()查看函数执行的情况,这个表中只有两条记录,得到的结果也是两条记录,说明存储函数成功的执行。

#3.创建一个存储过程add_id在同时使用前面创建的存储函数返回表sch中的记录数,计算出表中所有的id之和。
create procedure add_id(out count int)
begin
    declare itmp int;
    declare cur_id cursor for select id from sch;
    declare exit handler for not found close cur_id;
    
    select count_sch() into count;
    set @sum = 0;
    open cur_id;
    repeat
    fetch cur_id into itmp;
    if itmp < 10
    then set @sum = @sum + itmp;
    end if;
    until 0 end repeat;
    close cur_id;
end;
/**
 * 这个存储过程的代码中使用到了变量的声明、光标、流程控制、在存储过程中调用存储函数等知识点,结果应该是两条记录,
 * id之和为3,记录条数是通过上面的存储函数count_sch()获取的,是在存储过程中调用了存储函数。
 */

#查看
select @a,@sum;

 1.3变量的使用

  变量可以在子程序中声明并使用,这些变量的作用范围是在BEGIN END程序中。

  1.定义变量

    DECLARE 变量名【,变量名】 数据类型【DEFAULT value】;

    例:定义名称为myprama的变量,类型为int类型,默认值为100;

      DECLARE myprama INT DEFAULT 100;

  2.为变量赋值 定义变量之后,为变量赋值可以改变变量的默认值,MySQL中使用SET语句为变量赋值,语句格式如下:

    SET 变量名 = expr[,变量名 = expr];

作者:容一博

个性签名:我有一个不成熟的想法!

如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

原文地址:https://www.cnblogs.com/chromer/p/mysql_2.html