-- 声明变量 CREATEPROCEDURE pro_test() BEGIN DECLARE `变量名` `变量类型` DEFAULT `默认类型`; SELECT CONCAT('num的值:',num); end
-- 为变量进行赋值 set CREATEPROCEDURE pro_test1() BEGIN DECLARE num intDEFAULT0; set num = num+11; select num; end -- 为变量进行赋值 into CREATEPROCEDURE pro_test2() BEGIN DECLARE num int; SELECTCOUNT(*) into num from city; SELECT num; end
if条件判断
1 2 3 4 5 6 7 8 9 10
CREATEPROCEDURE pro_test3() BEGIN DECLARE height intDEFAULT175; DECLARE description VARCHAR(50) DEFAULT''; if height >=180thenset description ='身材高挑'; ELSEIF height <180AND height >=170thenset description ='身材标准'; ELSESET description ='身材一般'; END IF; SELECT CONCAT("身高:",height,"-身材类型:",description); end
CREATEPROCEDURE pro_test4(in mouth int) BEGIN DECLAREresultvarchar(10); CASE WHEN mouth >=1and mouth<=3THENsetresult='第一季度'; WHEN mouth >=4and mouth<=6THENsetresult='第二季度'; WHEN mouth >=7and mouth<=9THENsetresult='第三季度'; ELSEsetresult='第四季度'; ENDCASE; SELECT CONCAT("当前月份:",mouth,"-当前季度:",result) 'result'; END
WHILE循环
1 2 3 4 5 6 7 8 9 10 11 12 13
-- 1到n求和 CREATEPROCEDURE pro_test5(in n INT) BEGIN DECLARE total intDEFAULT0; DECLARE num intDEFAULT1;
WHILE num<=n DO set total = total+num; set num = num+1; END WHILE; SELECT total; END
REPEAT循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14
-- 满足条件退出循环,和while相反 -- 注意:util后面不加;不然报错 CREATEPROCEDURE pro_test6(in n INT) BEGIN DECLARE total intDEFAULT0; REPEAT set total = total + n; set n = n-1; UNTIL n=0 END REPEAT; SELECT total; END
LOOP循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14
-- 需要借助leave CREATEPROCEDURE pro_test7(in n INT) BEGIN DECLARE total intDEFAULT0; c:LOOP set total = total + n; set n = n-1; IF n<=0THEN LEAVE c; END IF; END LOOP c;
--新建一个游标 DECLARE city_result CURSORforSELECT c.*,t.country_name FROM city c,country t where c.country_id = t.country_id; --如果fetch取不到数据则会触发这句话 DECLARE EXIT HANDLER FORNOT FOUND set has_data =0;
OPEN city_result; REPEAT -- 每fetch一次,游标向下移动一次 FETCH city_result into c_id,c_name,c_country_id,c_country; SELECT CONCAT("id=",c_id,",name=",c_name,",cid=",c_country_id,",country=",c_country) "result"; UNTIL has_data =0 END REPEAT;
CLOSE city_result; END
函数
1 2 3 4 5 6 7 8 9 10 11
-- 主要是多了返回值 CREATEFUNCTION fun(countryId INT) RETURNSINT BEGIN DECLARE num INT; SELECTCOUNT(*) into num FROM city where country_id = countryId; RETURN num; END
-- 通过select调用 select fun(1)
触发器
1 2 3 4 5 6 7 8 9 10 11 12
-- 这里的new表示插入的数据 如果是old则表示修改前的数据 CREATETRIGGER `名字` AFTER INSERT--表示插入之后执行 可以更改 BEFORE UPDATE DELETE on `表名` forEACHROW--表示行级
BEGIN INSERTinto city_logs VALUES(null,'insert',now(),new.city_id,CONCAT('插入id=',new.city_id,',插入name=',new.city_name));