mysql学习--(六)--触发器、游标 、handler

触发器

删除员工表 的信息,自动添加到离职员工表中去
– delete 没有new,有old
– insert 没有old,有new
– update 有new,有old
– delete insert update 都是有两种触发方式(before、after)

create table leaveEmp as select * from emp;
delete from leaveemp;

drop trigger if exists Emp_del;

create trigger Emp_del after delete 
on emp for each row 
begin 
	 insert into leaveemp values (old.eno,old.ename,old.birthday,old.manager,old.job,old.sal,old.sex,old.comm,old.deptno);
end;

delete from emp where ename='tom';
select * from leaveEmp;

游标

初始化游标:
declare myCur cursor for select ename,sal from emp;

mysql学习--(六)--触发器、游标 、handler_第1张图片

drop procedure pro;
create procedure pro()
begin 
	declare i int default 0;
	declare v_sal float;
	declare num int default 0;
	declare v_ename varchar(20) default '暂时没有结果';
	declare myCur cursor for select ename,sal from emp;
	select count(*) into num from emp;
	-- 打开游标
	open myCur;
	-- 循环
	repeat 
		-- 定位一行数据
		fetch myCur into v_ename,v_sal;
		if v_sal>10000 then select v_ename,'白领';
		elseif v_sal>5000 then select v_ename,'蓝领';
		else select v_ename,'灰领' as 职称;
		end if;
		set i=i+1;
		until i>=num  end repeat;
	-- 关闭游标
	close myCur;
end;

call pro();

mysql错误检测handler-condition

declare continue handler for err1
continue–可持续
exit–停止

根据员工姓名,显示员工工资  handler必须在定义变量之后不然会报错
create procedure p7( en varchar(20))
begin 
	declare  rsal float default 0;
	-- 声明异常变量
	declare err1 condition for 1146;
	-- 错误处理
	declare continue handler for err1
		begin 
			select '您想访问的表不存在';
		end;
	select sal into rsal from emp2 where ename=en;
	select concat(en,'的工资是',rsal);
end
call p7('tom');

你可能感兴趣的:(mysql)