Home >Database >Mysql Tutorial >mysql中的触发器以及存储过程的基础了解_MySQL

mysql中的触发器以及存储过程的基础了解_MySQL

WBOY
WBOYOriginal
2016-06-01 13:41:53758browse

bitsCN.com mysql中的触发器以及存储过程的基础了解 触发器的基础了解: 01触发器(trigger):一触即发,就是当进行某种操作之后(或者之前),附加的一种操作就马上执行。02作用:监视某种情况并触发某种操作;03注意事项:04能监视的事件:增,删,改;能触发的事件:增,删,改;05 06监视地点:table07监视事件:insert/update/delete08触发时间:after/before09触发事件:insert/update/delete10 11#建立商品表:12    create table goods(goodsId int, name varchar(10), num int)charset utf8$13 14#建立订单表:15create table orders(ordersId int, goodsId int, num int)charset utf8$16 17#插入数据18insert into goods values(1,'猪',22),(2,'羊',19),(3,'狗',12),(4,'猫',8)$19 20#买三只羊21insert into orders values(1, 2, 3);22 23#减少羊的库存24update goods set num = num -3 where goodsId = 2;25 26#开始学着使用触发器27#监视地点:orders28#监视操作:insert29#触发操作:update30#触发时间:after31 32#创建第一个触发器33create trigger t134after insert on orders35for each row36begin37    update goods set num = num -3 where goodsId = 2;38    end$39 40#删除触发器41drop trigger t1$42 43#创建第二个触发器44create trigger t245after insert on orders46for each row47begin48    update goods set num = num - new.num where goodsId = new.goodsId;49end$50 51#创建第三个触发器52create trigger t353after delete on orders54for each row55begin    56    update goods set num = num + old.num where goodsId = old.goodsId;57end$58 59#创建第四个触发器60create trigger t461after update on orders62for each row63begin64    update goods set num = num + old.num - new.num where goodsId = old.goodsId;65end$存储过程的基础了解: 01存储过程的含义:02存储过程类似于函数,就是把一段代码封装起来,当要执行这一段代码的时候,可以通过调用该存储过程来实现。在封装的语句体里面,可以使用if/else, case, while等控制结构。这里面就有所谓的sql编程。03#测试表的建立及表的操作:04create table users( num int, name varchar(20), password varchar(20));05    insert into users values(1,'zwh','zwh');06insert into users values(2, 'lhy', 'lhy');07insert into users values(3, 'test', 'test');08insert into users values(4, 'test', 'test');09insert into users values(5, 'test', 'test');10insert into users values(6, 'test', 'test');11insert into users values(7, 'test', 'test');12insert into users values(8, 'test', 'test');13insert into users values(9, 'test', 'test');14insert into users values(10, 'test', 'test');15     16#查看存在的存储过程:17show procedure status;18 19#删除存在的存储过程:20drop procedure ***;21 22 23#这里先把定界符先改为$:24delimiter $25 26#建立第一个存储过程:体验一下"sql封装"27create procedure p1()28begin29    select * from users;30end$31 32#调用存储过程33call p1()$34 35#建立第二个存储过程:体验一下"参数"36create procedure p2( n int )37begin38    select * from users where num n;46    else47        select * from users where num

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn