存储的程序
========================================
* 数据库中存储的程序,对数据进行运算处理
* 存储过程
* 函数
* 触发器
会话变量
========================================
* 一次会话过程中,可以设置一些变量保存数据
* set @name='张三'
* @表示回话变量
* @@表示全局变量,指定是系统变量
set @@sql_mode='STRICT_TRANS_TABLES';
set @@autocommit=OFF
set sql_mode='STRICT_TRANS_TABLES';
set autocommit=OFF
* 显示变量的值
select @name, @a, @b, @c;
存储过程
==================================================
* 创建存储过程
delimiter // -- 设置语句的结束符号
create procedure p1()
begin
select * from t;
end;
//
delimiter ; -- 语句的结束符重新设置会成分号
* 调用存储过程
call p1();
* 删除存储过程
drop procedure [if exists] p1;
* 参数
存储过程的参数三种:
in 输入参数(默认)
out 输出参数
inout 即可输入也可输出
定义存储过程: p2(in a int, out b int)
...
...
set b = a*2;
调用 p2():
call p2(255, @v1)
select @v1;
* 流程控制
*)选择判断
if 条件 then
...
end if;
-----------------
if 条件 then
...
else
...
end if;
==========================
case
when 条件 then ...;
when 条件 then ...;
when 条件 then ...;
else ...;
end case;
*) 循环
while 条件 do
...
end while;
---------------
loop
...
end loop;
---------------
repeat
...
until 条件 end repeat;
---------------
leave 跳出循环
iterate 直接进入下次迭代
---------------
循环命名
lp: loop
leave lp;
iterate lp;
end loop;
* declare
定义局部变量
*) declare a int; -- null
*) declare a int default 1;
*) 局部变量在 end 结束时销毁
begin
declare a int default 1;
begin
declare b int default 2;
end;
select a; -- ok
select b; -- 错误
end;
函数
==================================================
* 与存储过程类似,
* 函数有返回值
* 用 select f() 调用函数
* 创建
create function f(参数) returns int
begin
....
return 计算结果;
end;
游标 cursor
==================================================
* 游标: 查询结果的数据指针
* 只能一步一步向下一行移动
* 不能任意的被定位
* 游标操作:
*)定义游标:
declare c cursor for select ...
*)打开游标:
open c;
*)从游标取一行数据(自动下移):
-- 从游标取出几个字段的数据,存入几个变量
fetch c into v1,v2,v3,v4;
*)关闭游标:
close c;
* 从头到尾用游标访问数据
mysql 的错误处理机制:
declare continue handler for ...
当出现指定错误(not found)时,执行一段代码(done=),
使程序可以继续正常执行(continue)
declare done int default 0;
declare c cursor for select ...
declare continue handler for not found set done=1;
open c;
while done=0 do
-- 在末尾取不到数据,会出现 not found 错误
-- 触发 done=1 执行
fetch c into ...
end while;
触发器
=============================================
* 对一行数据进行增删改操作,
可以触发一端代码执行
* 六种: 一张表最多就能创建6个触发器
before insert
before update
before delete
after insert
after update
after delete
* 创建触发器
create trigger 名称 before insert
on tb1 for each row
begin
....
end;
* 两个隐含对象
new - 新的数据行
old - 旧的数据行
new.id, new.name, new.price
old.id, old.name, old.price
*)插入操作
new - 新插入的一行数据
old - 没有
*)修改操作
new - 修改后的新数据
old - 修改前的旧数据
*)删除操作
new - 没有
old - 被删掉的数据