1. 程式人生 > >mysql 存儲過程中使用遊標中使用臨時表可以替代數組效果

mysql 存儲過程中使用遊標中使用臨時表可以替代數組效果

效果 tmp declare ges 必須 eight bold lar ora

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 存儲過程中使用遊標中使用臨時表可以替代數組效果