DECLARE命名游标,并定义相应的SELECT语句
e.g.
CREATE PROCEDURE processorders()
BEGIN
-- Declare the cursor
DECLARE ordernumbers CURSOR
FOR
SELECT order_num FROM orders;
-- Open the cursor
OPEN ordernumbers;
-- Close the cursor
CLOSE ordernumbers;
END;
这就是一个简单的游标示例
打开和关闭游标
OPEN ordernumbers;
CLOSE ordernumbers;
使用游标
游标被打开后,可以使用FETCH语句来访问它的每一行,FETCH制定检索什么数据,检索出来的数据存储在什么地方。
CREATE PROCEDURE processorders()
BEGIN
-- Declare loacl 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 TALBE 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;
-- Get the total for this order
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;
这个例子中,增加了一个名为t的变量存储每个订单的合计,此存储过程还在运行中创建了一个新表,名为ordertotals.这个表将保存存过程生成的结果,FETCH取每一个order_num,然后用CALL执行另一个存储过程来计算每个订单的带税合计,最后用insert保存每个订单的订单号和合计