《数据库系统实训》实验报告——游标
生活随笔
收集整理的這篇文章主要介紹了
《数据库系统实训》实验报告——游标
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
游標
第一部分:樣例庫的應用
1)創建游標
CREATE PROCEDURE processorders() BEGINDECLARE ordernumbers CURSORFORSELECT order_num FROM orders; END由于沒有打開游標,此過程不會把數據檢索出來。
2)使用游標數據
查詢結果:
3)循環檢索數據
CREATE PROCEDURE processorders() BEGIN -- Declare local variables DECLARE done BOOLEAN DEFAULT 0; DECLARE o INT; -- Declare the cursor DECLARE ordernumbers CURSOR FOR SELECT order_num FROM orders; -- Declare continue handler DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1; -- Open the cursor OPEN ordernumbers; -- Loop through all rows REPEAT -- Get order number FETCH ordernumbers INTO o; SELECT o; -- End of loop UNTIL done END REPEAT; -- Close the cursor CLOSE ordernumbers; END; ```查詢結果:4)循環處理數據 ```sql 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,SQLSTATE '02000' 是一個“未找到”條件 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; -- 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;處理結果:
第二部分:所選課題數據庫的應用
1)查詢語句:
CREATE PROCEDURE `calculateprice`() BEGINDECLARE done BOOLEAN DEFAULT 0; DECLARE o INT;DECLARE t INT;DECLARE remainss CURSORFORSELECT goods_id FROM order_detail;CREATE TABLE IF NOT EXISTS pricetotals(id INT,total INT);OPEN remainss;REPEATFETCH remainss INTO o;CALL pricetotal(o,t);INSERT INTO pricetotals(id,total)VALUES(o,t);UNTIL done END REPEAT;CLOSE remainss; END以下為創建用來計算price*remains的函數:
CREATE PROCEDURE `pricetotal`(IN `inumber` int,OUT `ptotal` decimal) BEGIN#Routine body goes here...SELECT Sum(total_price)FROM order_detailWHERE goods_id = inumberINTO ptotal; END查詢結果:
參考文章
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的《数据库系统实训》实验报告——游标的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《数据库系统实训》实验报告——存储过程
- 下一篇: 《数据库系统实训》实验报告——触发器