1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | | create procedure procedureName() begin -- 通过在begin和end之间写sql并批量执行,begin和end是固定的写法 --通过declare关键字定义变量,下面语句的含义是定义了一个叫age的整型变量默认值是18 declare age int default 18; declare height int default 180; select ('年龄是',age,'身高是',height); end create procedure p2() begin declare age int default 11; select concat('年龄是',age); end --set关键字的用法是给定义的变量赋值 create procedure p3() begin -- 下面的含义 定义一个叫age的变量,并给其加上10,并在控制台显示出来 declare age int default 15; set age := age+10; select concat('10年后的年龄是',age); end$ --逻辑判断之if-else分支结构 create procedure procedureName() begin declare age int default 18; if age >= 18 then select concat('已成年',''); else select concat('未成年',''); end if; end --逻辑判断之if-elseif-else分支结构,and表示逻辑与 or表示逻辑或 create procedure p5() begin declare v int default 49; if v >0 and v <= 10 then select '0<v<10'; elseif v > 10 and v <= 50 then select '10 < v <=50'; else select 'v > 50'; end if; end $ --逻辑判断之case-when-then-else分支结构 create procedure px24() begin declare randNum int default 0; set randNum := floor(rand()*5); case randNum when 1 then select '1' as result; when 2 then select '2' as result; when 3 then select '3' as result; else select 'i dont konw'; end case; end$$
--循环之while循环结构举例,以while开头 end while结束 create procedure px16() begin declare sum int default 0; declare i int default 1; -- 每次循环一次对i+1,知道i<=100不满足为止 while i<=100 do set sum := sum+i; set i := i+1; end while; select concat('1+...+100=',sum); end$$ --循环之repeat循环结构举例,知道满足util之后条件后结束 create procedure p11() begin declare i int default 2; repeat select concat('i=',i); set i := i-1; until i <= 0 end repeat ; end$ |