mysql的cursor使用(游标)脚本创建

环境:win7,mysql5.5

参考:http://blog.csdn.net/kupepoem/article/details/15816083(mysql学习入门)

参考:mysql必知必会

 

由于我使用的是mysql命令行实用程序,会将‘;’当着结束符。在写存储过程时,可以先delimiter //一下,先将'//'当着分离符,最后再delimiter ;。在写存储过程时,如果不把存储过程写成脚本,有点错误就得重新写,这可不行啊。。。。

1、创建脚本

下面是cursor.sql的脚本内容:

DELIMITER //

CREATE PROCEDURE processorders()
BEGIN

#Declare local variables
DECLARE done BOOLEAN DEFAULT 0;
DECLARE o INT;
DECLARE t DECIMAL(8,2);

#Declare the cursor
DECLARE ordernumbers CURSOR
FOR
SELECT order_num FROM orders;

#Declare continue handler

DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

#Create a table to store the results
CREATE TABLE IF NOT EXISTS ordertotals(order_num INT,total DECIMAL(8,2));

#open the cursor
OPEN ordernumbers;

#Loop through all rows

REPEAT

#Get order number

FETCH ordernumbers INTO o;

CALL ordertotal(o,1,t);

#Insert order and total into ordertotals 
INSERT INTO ordertotals(order_num,total)
VALUES(o,t);

#End of loop
UNTIL done END REPEAT;

#close the cursor

close ordernumbers;
end//

DELIMITER ;

2、运行脚本

source F:\software\mysql_scripts\cursor.sql

3、检查运行结果

select * from ordertotals;

mysql的cursor使用(游标)脚本创建_第1张图片

 

 

你可能感兴趣的:(mysql的cursor使用(游标)脚本创建)