ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Mysql存储过程

Mysql存储过程 show global variables #查看全局变量set global 全局变量 #设置全局变量的值show session variables #查看会话变量局部变量使用declare 定义局部变量#创建存储过程say:delimiter // create procedure tarena.say48()begindeclarex int default9;declarey char(10);setyplj;selectx,y;end // delimiter;#调用存储过程call tarena.say48();用户变量的使用(当前连接的用户有效)定义set age 19;调用select age参数的使用in: 把数据传给存储过程out接受存储过程处理的结果inout都有IN:#根据部门编号统计部门的总人数delimiter // create procedure tarena.pnum(in dept_no int)beginselectdept_id as 部门编号count(name)as 总人数 from employements wheredept_iddept_no group by dept_id;end // delimiter;call tarena.pnum(6)OUT:#根据员工姓名 获取员工的邮箱delimiter // create procedure tarena.pmail(in ename char(10), out yx char(50))beginselectemail into yx from employees wherenameename;end // delimiter;call tarena.pmail(刘倩,x);# x保存处理的结果INOUT: delimiter // create procedure tarena.myadd(inout i int)beginsetii100;end // delimiter;setx7;call tarena.myadd(x);存储过程-流程控制if语句if条件1then语句1;elseif 条件2then语句2;else语句3;endif;例子delimiter // create procedure tarena.deptype_pro(in no int,out dept_type varchar(5))begindeclaretypevarchar(5);selectdept_name intotypefrom departments wheredept_idno;iftype运维部thensetdept_type技术部;elseiftype开发部thensetdept_type技术部;elseiftype测试部thensetdept_name技术部;elsesetdept_name非技术部;endif;end // delimiter;call tarena.deptype_pro(1,t);case语句case变量|表达式|字段 when 值1then返回值1;when 值2then返回值2;...else返回值n;endcase;例子delimiter // create procedure tarena.deptype_pro2(in no int,out dept_type varchar(5)) begin declare type varchar(5); select dept_name into type from departments where dept_idno; case type when 运维部 then set dept_type技术部; when 开发部 then set dept_type技术部; when 测试部 then set dept_type技术部; else set dept_type非技术部; end case; end // delimiter ; call deptype_pro2(3,t);循环语句while循环条件成立时执行代码条件不成立 会直接结束循环while判断条件do代码 endwhile;例子delimiter // create procedure tarena.while_pro(in i int)begindeclarej int default1;whilejidoinsert into departments(dept_name)values(hr);setjj1;endwhile;end // delimiter;call while_pro(2);loop循环没有判断条件重复执行同一段代码只要不人为结束就一直执行所以称为死循环。loop 代码 end loop;例子delimiter // create procedure tarena.loop2()begindeclarei int default1;loopselectsleep(1), i;end loop;end // delimiter;call loop2;mysqlshow processlist;#相当于ps -auxmysqlkillID号;repeat循环先循环一次再判断条件条件不成立继续执行条件成立结束循环。repeat 循环体until判断条件 end repeat;例子delimiter // create procedure tarena.repeat_pro(in i int)begindeclarej int default1;repeatsetjj1;insert into departments(dept_name)values(sales);untilji;end repeat;end // delimiter;call repeat_pro(4);循环控制语句leave结束循环相当于breakdelimiter // create procedure tarena.p0()begin xixi:loop leave xixi;selectsleep(1);selectone;end loop xixi;end // delimiter;iterate终止当前循环并开始下次循环相当于continuedelimiter // create procedure tarena.p3(in i int)begindeclarej int default1;haha:while jidoifj3thensetjj1;iterate haha;endif;selectj;setjj1;endwhilehaha;end // delimiter;call p3(4);
返回列表