MySql自定义函数或存储过程

我这里有三张表

A表
id 起始时间 结束时间

B表
id 时间 金额

C表
id 起始时间 结束时间 总金额 总笔数

现在的需求是传入一个时间值从A表里查出时间段,然后在B表里统计这个时间段的总金额、总笔数,再连同起始时间和结束时间一起插入到C表里。

我不知道这样的流程能不能用MySql的存储过程或者函数是否能实现,我自己想了很久没有写出来,如果用存储过程或者函数能实现,应该怎么写。

[code="sql"]
BEGIN
DECLARE c_start bigint(50);
DECLARE c_end bigint(50);
DECLARE c_total_money float(11);
DECLARE c_total_quantity int(11);
select 起始时间,结束时间 from A where start_time>=传入的时间 and 传入的时间<=end_time LIMIT 0,1 INTO @c_start,@c_end;
select count(id),sum(金额) from B where 时间>=@c_start and 时间<=@c_end into @c_total_quantity,@c_total_money;
insert into C(起始时间,结束时间,总金额,总数量) values(@c_start,@c_end,@c_total_money,@c_total_quantity);
RETURN 0;
END
[/code]