mysql 預存程序中使用遊標中使用暫存資料表可以替代數組效果

來源:互聯網
上載者:User

標籤:set   open   loop   使用   cal   聲明   關閉   rom   truncate   

mysql不支援數組。但有時候需要組合幾張表的資料,在預存程序中,經過比較複雜的運算擷取結果直接輸出給調用方,比如合格幾張表的某些欄位的組合計算,mysql暫存資料表可以解決這個問題.暫存資料表:只有在當前串連情況下, TEMPORARY 表才是可見的。當串連關閉時, TEMPORARY 表被自動取消。必須擁有 create temporary table 許可權,才能建立暫存資料表。可以通過指定 engine = memory; 來指定建立記憶體暫存資料表。

先建立要用的資料表及資料:

drop table if exists  person;create table `person` (  `id` int(11)primary key NOT NULL DEFAULT ‘0‘,  `age` int(11) DEFAULT NULL,  `name` varchar(225) not null) engine=innodb default charset=utf8;insert into person values(1,1,‘zhangshan‘),(2,2,‘lisi‘),(3,3,‘lst‘),(4,4,‘jon‘),(5,5,‘test‘);

暫存資料表支援主鍵、索引指定。在串連非暫存資料表查詢可以利用指定主鍵或索引來提升效能。預存程序語句及遊標和暫存資料表綜合執行個體:

drop procedure if exists sp_test_tt; -- 判斷預存程序函數是否存在如果是刪除delimiter ;;create procedure  sp_test_tt()  begin           create temporary table if not exists tmp   -- 如果表已存在,則使用關鍵詞 if not exists 可以防止發生錯誤         (             id varchar(255) ,             name varchar(50),             age varchar(500)         ) engine = memory;           begin          declare ids int; -- 接受查詢變數        declare names varchar(225); -- 接受查詢變數        declare done int default false; -- 跳出標識        declare ages int(11); -- 接受查詢變數        declare cur cursor for select id from person; -- 聲明遊標        declare continue handler for not FOUND set done = true; -- 迴圈結束設定跳出標識        open cur; -- 開始遊標        LOOP_LABLE:loop -- 迴圈            FETCH cur INTO ids;            select name into names from person where id=ids;            select age into ages from person where id=ids;            insert into tmp(id,name,age) value(ids,names,ages);            if done THEN  -- 判斷是否繼續迴圈如果done等於true離開迴圈                LEAVE LOOP_LABLE; -- 離開迴圈            END IF;            end LOOP; -- 結束迴圈        CLOSE cur; -- 關閉遊標     select * from tmp; -- 查詢暫存資料表         end;           truncate TABLE tmp;   -- 使用 truncate TABLE 的方式來提升效能end;  ;;delimiter ;;

執行預存程序:

call sp_test_tt();

mysql 預存程序中使用遊標中使用暫存資料表可以替代數組效果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.