mysql存储过程和存储函数
-
存数函数
代码示例:DROP PROCEDURE IF EXISTS calc_ci_day_suc_rate;
delimiter //
CREATE FUNCTION calc_ci_day_suc_rate(dt DATE, exp_version VARCHAR(64)) RETURNS FLOAT
BEGIN
DECLARE oneDayCICount INT DEFAULT 0;
DECLARE oneDaySucCICount INT DEFAULT 0;
DECLARE CISucRate FLOAT DEFAULT -1.0;
SELECT COUNT(build_id) INTO oneDayCICount FROM versions_build_info WHERE version_name = exp_version AND DATEDIFF(generate_time, dt) = 0;
IF(oneDayCICount != 0) THEN
SELECT COUNT(distinct(build_id)) INTO oneDaySucCICount FROM build_detail WHERE build_detail where result=1 and build_id in (select build_id from versions_build_info where version_name = exp_version and DATEDIFF(generate_time, dt) = 0);
SET CISucRate = oneDaySucCICount*100/oneDayCICount;
END IF
RETURN CISucRate
END
//
delimiter ;其中的delimiter是改变mysql命令行中;结束符为//,当然,也可以改为其他的符号
存储函数创建的基本格式为:CREATE FUNCTION 函数名(参数名 类型, 参数名 类型)RETURNS 返回值类型
BEGIN
DECLARE 参数名 类型 [DEFAULT 值];
IF(表达式) THEN
SET 变量名 = 值;
ELSEIF(表达式) THEN
语句块;
ELSE
语句块;
END IF;
WHILE 表达式 DO
语句块;
END WHILE;
RETURN 参数名;
END- CREATE FUNCTION是表示创建的是存储函数,后跟函数名和参数
- RETURNS后面跟的是返回值的类型
- 函数体是以BEGIN开始,END结束
- 函数中局部变量的声明使用DECLARE,类型就是mysql支持的类型,可以通过DEFAULT指定缺省值
- 变量的赋值通过SET进行
- IF来进行条件判断,以END IF结束
- WHILE循环以END WHILE结束
-
存储过程
代码示例:DROP PROCEDURE IF EXISTS cacl_all_ci_suc_rate;
delimiter //
CREATE PROCEDURE cacl_all_ci_suc_rate(IN exp_version VARCHAR(64))
BEGIN
DECLARE beginDate DATETIME DEFAULT '2015-01-01';
DECLARE caclDate DATE;
DECLARE CISucRate FLOAT DEFAULT -1.0;
DECLARE oneDayCICount INT DEFAULT 0;
DECLARE oneDayFailCICount INT DEFAULT 0;
DECLARE oneDaySucCICount INT DEFAULT 0;
SELECT MIN(generate_time) INTO beginDate FROM versions_build_info;
IF(DATEDIFF(beginDate, '2015-01-01') != 0) THEN
SET caclDate = DATE(beginDate);
WHILE DATEDIFF(CURDATE(), caclDate) > 0 DO
SELECT get_one_day_total_ci_count(caclDate, exp_version) INTO oneDayCICount;
IF(oneDayCICount != 0) THEN
SELECT get_one_day_fail_ci_count(caclDate, exp_version) INTO oneDayFailCICount;
SET oneDaySucCICount = oneDayCICount - oneDayFailCICount;
SET CISucRate = oneDaySucCICount*100/oneDayCICount;
INSERT INTO rmp_daily_build_ci(ci_date, suc_percent, build_count, suc_count) VALUES(caclDate, CISucRate, oneDayCICount, oneDaySucCICount);
END IF;
SET caclDate = ADDDATE(caclDate, 1);
END WHILE;
END IF;
END
//
delimiter ;- CREATE PROCEDURE表示创建存储过程
- 参数可以通过IN和OUT来表示参数是输入参数还是输出参数,INOUT表示既是输入也是输出
- 没有返回值
- 其他语法与创建存数函数一样