mysqlストレージ・プロシージャ、カーソルおよび逐行処理の組み合わせ

2277 ワード

1.データ準備
+----+------+--------+
| id | name | price1 |
+----+------+--------+
|  1 |    | 5      |
|  2 |    | 4.5    |
|  3 |    | 6      |
|  4 |    | 4      |
|  5 |    | 5.5    |
+----+------+--------+

2.次のストアド・プロシージャ呼び出し用のストアド・プロシージャの定義
delimiter //
create procedure getPrice1(
    in id int,
    in addSelf boolean,
    out ototal decimal(6,2)
) comment '  id      2     '
begin
    --       price
    declare price decimal(6,2);
    --   id  price1       price 
    select price1 from aa01 where aa01.id = id into price;
    --        2
    if addSelf then
        select price * 2 into price;
    end if;
    --               
    select price into ototal;
end //
delimiter ;

3.ストアド・プロシージャ、カーソルおよびプログレッシブ処理の組み合わせ
delimiter //
create procedure copyIdAndDoublePrice1()
comment '     id price1*2      aa02 '
begin
	--       
	declare done boolean default 0;
	declare tempId int;
	declare tempDoublePrice1 decimal(6,2);
	--     
	declare idIndex cursor
	for
		select id from aa01;
	--         
	declare continue handler for sqlstate '02000' set done = 1;
	--   aa02        
	create table if not exists aa02(
		id int,
		doublePrice1 decimal(6,2)
	);
	--     
	open idIndex;
	--      
	repeat
		--        id
		fetch idIndex into tempId;
		--              
		call getPrice1(tempId, 1, tempDoublePrice1);
		--      aa02 
		insert into aa02(id, doublePrice1) values (tempId, tempDoublePrice1);
	--     
	until done end repeat;
	--     
	close idIndex;
end //
delimiter ;

4.ストアド・プロシージャおよびクエリー・テーブルaa 02の呼び出し結果
call copyIdAndDoublePrice1();
select * from aa02;
+----+--------------+
| id | doublePrice1 |
+----+--------------+
|  1 | 10           |
|  2 | 9            |
|  3 | 12           |
|  4 | 8            |
|  5 | 11           |
|  5 | 11           |
+----+--------------+

5.注意事項
この文は、条件が発生したときに実行されるコードであるCONTINUE HANDLERを定義します.ここで、SQLSTATE'02000'が現れると、SET done=1となることを示す.SQLSTATE'02000'は、REPEATがより多くの行供給サイクルがないため続行できない場合に発生する条件が見つからない.
DECLARE文の順序DECLARE文のパブリケーションには、特定の順序があります.DECLARE文で定義されるローカル変数は、任意のカーソルまたはハンドルを定義する前に定義する必要があり、ハンドルはカーソルの後に定義する必要があります.この順序を守らないとエラーメッセージが発生します.