服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Mysql - Mysql存储过程、触发器、事件调度器使用入门指南

Mysql存储过程、触发器、事件调度器使用入门指南

2022-09-08 17:53长不大的大灰狼 Mysql

存储过程(Stored Procedure)是一种在数据库中存储复杂程序的数据库对象。为了完成特定功能的SQL语句集,经过编译创建并保存在数据库中,本文给大家介绍Mysql存储过程、触发器、事件调度器使用入门指南,感兴趣的朋友一起看看

存储过程(Stored Procedure)是一种在数据库中存储复杂程序的数据库对象。为了完成特定功能的SQL语句集,经过编译创建并保存在数据库中。

一、存储过程的简单使用

创建存储过程

?
1
2
3
4
create procedure test()
begin
    select * from users;
end;

调用存储过程

?
1
call test();

二、存储过程中的变量

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
create procedure test()
begin
 
  -- 使用 declare语句声明一个变量
  declare username varchar(32) default '';
  
  -- 使用set语句给变量赋值
  set username='xiaoxiao';
  
  -- 将users表中id=1的名称赋值给变量username
  select name into username from users where id=1;
  
  -- 返回变量
  select username;
end;

注意:

  • 变量可以通过set来赋值,也可以通过select into的方式赋值;
  • 变量需要返回,可以使用select语句,如:select 变量名。

三、变量的作用域

存储过程的作用域在begin和end块之间,变量声明在begin之外,可以作为全局变量使用:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
create procedure test()
   begin
     declare userscount int default 0; -- 用户表中的数量
     begin
           select count(*) into userscount from users;
           select userscount; -- 返回用户表中的数量
     end;
     begin
       declare maxmoney int default 0; -- 最大金额
       select max(money) into maxmoney from orders;
       select userscount,maxmoney; -- 返回用户表中的数量、最大金额
      end;
   end;

四、存储过程参数

?
1
2
3
4
create procedure 名称([IN|OUT|INOUT] 参数名 参数数据类型 )
begin
......
end

IN: 传入参数(不指定时,默认就是IN类型)

?
1
2
3
4
5
6
create procedure test(userId int)
   begin
       declare username varchar(32) default '';
       select name into username from users where id=userId;
       select username;
   end;

OUT:传出参数

?
1
2
3
4
create procedure test(in userId int,out username varchar(32))
   begin
     select name into username from users where id=userId;
   end;

INOUT: 既是传入又是传出参数

?
1
2
3
4
5
6
create procedure test6(inout userId int,inout username varchar(32))
begin
    set userId=2;
    set username='';
    select id,name into userId,username from users where id=userId;
end;

五、逻辑控制语句

1、条件语句

?
1
2
3
4
if() then...
elseif() then...
else ...
end if;
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
create procedure test(in userid int)
begin
   declare my_status int default 0;
   select status into my_status from users where id=userid;
   
   if(my_status=1)
   then
       update users set score=score+10 where id=userid;
   elseif(my_status=2)
   then
       update users set score=score+20 where id=userid;
   else
       update users set score=score+30 where id=userid;
   end if;
end;

2、循环语句

(1)while

?
1
2
3
while(表达式) do
   ...... 
end while;
?
1
2
3
4
5
6
7
8
9
10
11
create procedure test()
begin
  declare i int default 0;
  while(i<10) do
     begin
        select i;
        set i=i+1;
        insert into test1(id) values(i);
     end;
  end while;
end;

(2)repeat

?
1
repeat...until...end repeat;

只有当until为真是才跳出循环:

?
1
2
3
4
5
6
7
8
9
10
11
12
create procedure test()
begin
    declare i int default 0;
    repeat
     begin
        select i;
        set i=i+1;
        insert into test1(id) values(i);
     end;
    until i>=10 -- 如果i>=10,则跳出循环
    end repeat;
end;

3、case分支

?
1
2
3
4
5
case ...
when ... then....
when.... then....
else ...
end case;
?
1
2
3
4
5
6
7
8
9
10
11
12
create procedure testcate(userid int)
   begin
       declare my_status int default 0;
       select status into my_status from users where id=userid;
 
       case my_status
           when 1 then update users set score=10 where id=userid;
           when 2 then update users set score=20 where id=userid;
           when 3 then update users set score=30 where id=userid;
           else update users set score=40 where id=userid;
       end case;
   end;

六、游标

游标保存了查询结果的临时区域

?
1
2
declare 变量名 cursor ... -- 创建一个游标变量
close 变量名; -- 关闭游标
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
create procedure test()
    begin
        declare stopflag int default 0;
        declare username VARCHAR(32);
        declare username_cur cursor for select name from users where id%2=0;
        -- 游标变量username_cur保存了查询的临时结果,即结果集
        -- 在游标变量中数据的结尾,将变量stopflag设置为1,用于循环中判断是否结束
        declare continue handler for not found set stopflag=1;
 
        open username_cur; -- 打卡游标
        fetch username_cur into username; -- 游标向前走一步,取出一条记录放到变量username中
        while(stopflag=0) do -- 如果游标还没有结尾,就继续
            begin
                -- 在用户名前门拼接 '_cur' 字符串
                update users set name=CONCAT(username,'_cur') where name=username;
                fetch username_cur into username;-- 游标向前走一步,取出一条记录放到变量username中
            end;
        end while; -- 结束循环
        close username_cur; -- 关闭游标
    end;

七、自定义函数

?
1
2
3
4
5
6
7
8
-- 创建函数
create function 函数名(参数) returns 返回类型;
-- 函数体
begin ...... end
-- 指定函数的返回值
returns
--函数调用
select 函数名()。
?
1
2
3
4
5
6
7
create function getusername(userid int) returns varchar(32)
    reads sql data  -- 从数据库中读取数据,但不修改数据
    begin
        declare username varchar(32) default '';
        select name into username from users where id=userid;
        return username;
    end;

八、触发器

触发器也是一种数据库对象,在满足定义条件时触发,并执行触发器中定义的语句集合。

创建触发器create trigger 触发器名
after、before:在对表操作之前(before)或者之后(after)触发动作。
操作事件:insert,update,delete等修改操作
影响的范围:for each row

1、需求:出于审计目的,当有人往表users插入一条记录时,把插入的userid,username,插入动作和操作时间记录下来。

?
1
2
3
4
5
6
create trigger tr_users_insert after insert on users
    for each row
    begin
        insert into oplog(userid,username,action,optime)
        values(NEW.userid,NEW.name,'insert',now());
    end;

2、需求:出于审计目的,当删除users表时,记录删除前该记录的主要字段值

?
1
2
3
4
5
6
create trigger tr_users_delete before delete on users
    for each row
    begin
        insert into oplog(userid,username,action,optime)
        values(OLD.id,OLD.name,'delete',now());
    end;

九、事件

触发器只是针对某个表产生的事件执行一些语句,而事件调度器则是在某一个(间隔)时间执行一些语句。

在使用这个功能之前必须确保事件调度器event_scheduler已开启:

?
1
2
3
4
5
6
SET GLOBAL event_scheduler = 1;
-- 或者
SET GLOBAL event_scheduler = on;
 
--查看开启情况
show variables like '%event_scheduler%';
?
1
2
3
4
5
6
create event[IF NOT EXISTS]event_name -- 创建使用create event
    ON SCHEDULE schedule -- on schedule 什么时候来执行
    [ON COMPLETION [NOT] PRESERVE] -- 调度计划执行完成后是否还保留
    [ENABLE | DISABLE] -- 是否开启事件,默认开启
    [COMMENT 'comment'] -- 事件的注释
    DO sql_statement; -- 这个调度计划要做什么?

需求:设计一个福彩的开奖过程,每3分钟开奖一次

?
1
2
3
4
5
6
-- 存储过程
create procedure test()
        begin
            insert into lottery(num1,num2,num3,ctime)
            select FLOOR(rand()*9)+1,FLOOR(rand()*9)+1,FLOOR(rand()*9)+1,now();
        end;
?
1
2
3
4
5
-- 事件
create event if not exists test_event -- 创建一个事件
        on schedule every  3 minute -- on schedule 每三分钟执行一次
        on completion preserve
        do call test;  --调用存储过程

参考文章:mysql存储过程学习笔记

到此这篇关于Mysql存储过程、触发器、事件调度器使用入门的文章就介绍到这了,更多相关Mysql存储过程、触发器、事件调度器内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/glpghz/article/details/122568682

延伸 · 阅读

精彩推荐
  • MysqlMySQL系列之十三 MySQL的复制

    MySQL系列之十三 MySQL的复制

    这篇文章主要介绍了MySQL系列之十三 MySQL的复制,详细的讲述了多种复制架构的案例和MySQL复制相关概念等,以下就是详细内容,需要的朋友可以参考下...

    生生不息.连绵不绝12102021-08-27
  • Mysqlhive从mysql导入数据量变多的解决方案

    hive从mysql导入数据量变多的解决方案

    这篇文章主要介绍了hive从mysql导入数据量变多的解决方案,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    京东8682021-03-27
  • MysqlLinux(Ubuntu)下Mysql5.6.28安装配置方法图文教程

    Linux(Ubuntu)下Mysql5.6.28安装配置方法图文教程

    这篇文章主要为大家详细介绍了Linux(Ubuntu)下Mysql5.6.28安装配置方法图文教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 ...

    AskTommorow5922020-07-12
  • Mysql关于Mysql自增id的这些你可能还不知道

    关于Mysql自增id的这些你可能还不知道

    这篇文章主要给大家介绍了关于Mysql自增id的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Mysql具有一定的参考学习价值,需要的朋友...

    kun_jian5612020-09-24
  • Mysqlmysql下为数据库设置交叉权限的方法

    mysql下为数据库设置交叉权限的方法

    由于 SupeSite 需要调用 Discuz! 和 UCHome 的数据,所以如果它们不安装在同一个数据库,SupeSite 的数据库用户必须要对 Discuz! 和 UCHome 的数据库有读取、修改、...

    MYSQL教程网3662019-11-20
  • MysqlMySQL全面瓦解之查询的正则匹配详解

    MySQL全面瓦解之查询的正则匹配详解

    这篇文章主要给大家介绍了关于MySQL全面瓦解之查询的正则匹配的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学...

    翁智华4812021-03-04
  • Mysqlmysql查询结果输出到文件的方法

    mysql查询结果输出到文件的方法

    下面小编就为大家带来一篇mysql查询结果输出到文件的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    MYSQL教程网3912020-07-09
  • Mysql论一条select语句在MySQL是怎样执行的

    论一条select语句在MySQL是怎样执行的

    本文将建立一套建立一套MySQL的知识框架,通过讨论select语句在MySQL是怎样执行的来展开内容,感兴趣的小伙伴一起来看下文吧...

    咔咔-10752021-09-24