delimiter $ createprocedure procedure_test01() begin declare name varchar(20); set name ='mysql'; select name; end$ delimiter ;
也可以通过select…into方式进行赋值操作;
1 2 3 4 5 6 7 8
delimiter $ createprocedure procedure_test02() begin declare num intdefault0; selectcount(*) into num from stu; select num; end$ delimiter ;
5.2 if判断
1 2 3 4 5 6 7 8 9
if search_condition then statement_list [elseif search_condition then statement_list]... [else statement_list] end if; 示例: 根据定义的身高变量,来判断所属身材类型. 180及以上:身材高挑, 170-180:标准身材, 170及以下,一般身材
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
delimiter $ createprocedure procedure_test03() begin declare hight intdefault182; declare description varchar(10) default''; if hight>=180then set description ='身材高挑'; elseif hight>=170and hight<180then set description ='标准身材'; else set description ='一般身材'; end if; select concat('身高',hight,'对应的身材类型为',description); end$ delimiter ;
/* 需求: 给定一个月份,然后计算是哪一季度 */ delimiter $ createprocedure procedure_test06(mon int,out jidu varchar(10)) begin case mon when mon>=1and mon<=3then set jidu='第一季度'; when mon>=4and mon<=6then set jidu='第二季度'; when mon>=7and mon<=9then set jidu='第三季度'; else set jidu='第四季度'; endcase; select concat(mon,'是',jidu); end$ delimiter ;
5.5 while循环
1 2 3 4 5
while search_condition do statement_list end while; 需求: 计算从1到n的累加值
1 2 3 4 5 6 7 8 9 10 11 12
delimiter $ createprocedure procedure_test07(n int) begin declare total intdefault0; declarestartintdefault1; while start<=n do set total=total+start; setstart=start+1; end while; select total; end$ delimiter ;
repeat statement_list until search_condition(注意这里没有';') end repeat; 需求: 计算从1到n的累加值
1 2 3 4 5 6 7 8 9 10 11 12
delimiter $ createprocedure procedure_test08(n int) begin declare total intdefault0; repeat set total=total+n; set n=n-1; until n<=0 end repeat; select total; end$ delimiter ;