发布网友 发布时间:2022-04-23 17:34
共2个回答
热心网友 时间:2022-04-15 07:49
考虑下面的需求,在一段时间内,间隔一段时间,取一个平均值,把所有的平均值取出来,怎么办?
思路:在存储过程中,拼接sql语句。根据起始时间和结束时间,while循环每次加一段时间。
DROP PROCEDURE IF EXISTS `get_avg`;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `get_avg`(in iStartTime datetime, in iEndTime datetime)
BEGIN
declare vSql varchar(10240) default '';
declare vNextTime datetime;
while(iStartTime < iEndTime) do
-- 每次加一个小时
set vNextTime = date_add(iStartTime,interval 3600 second);
-- 单引号是特殊字符,要表示单引号,使用 '' 进行转义
set vSql = concat(vSql,'union select 100, avg(`value`) from t1 where time between ''',iStartTime,''' and ''', vNextTime,''' ');
set iStartTime = vNextTime;
end while;
set vSql = substring(vSql,7);
-- 看看拼接的字符串是否正确
-- select vSql;
set @vSql = vSql;
prepare stmt from @vSql;
execute stmt;
deallocate prepare stmt;
END
;;
DELIMITER ;
热心网友 时间:2022-04-15 09:07
declare not_exists int default 0;
declare $id int;
declare $phone varchar(50);
DECLARE $_error INT DEFAULT 0;
#定义游标接受表查询数据
declare cur1 cursor for select id,avg(phone) as ph from ht_user u
where create_date between date_sub(create_date, interval 30 day) and create_date group by id;
/**********sql查询结果异常处理**********/
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET $_error=1;
declare continue handler for not found set not_exists=1;
/*************外部参数赋值**************/
/***************开始事务****************/
#读取表中的数据循环输出
open cur1;
while(not_exists!=1) do
fetch from cur1 into $id,$phone;
update ht_user t set t.test = $phone where id = $id;
end while;
close cur1;
#2 报错处理
if($_error=1) then
rollback;
else
commit;
end if;
select $_error as errorCode;