MySQL PLSQL Demo - 004.(临时表或视图)模拟动态SQL(游标)

参考:写MySQL存储过程实现动态执行SQL,也可以用临时表模拟动态SQL的效果。

参考:Dynamic cursor in stored procedure,可以使用临时表或视图实现,并分析了各自的优劣。

 

使用view

drop procedure if exists p_simulate_dynamic_cursor;



create procedure p_simulate_dynamic_cursor()

begin

    declare v_sql varchar(4000);

        declare v_field varchar(4000);

        declare v_result varchar(4000) default '';

        declare cur_temp cursor for select v.* from view_temp_20150701 v;

        declare continue handler for not found set v_field = null;



        set v_sql = 'create view view_temp_20150701 as select t.id from t_user t';

        

        set @v_sql = v_sql;

        prepare statement from @v_sql;

        execute statement;

        deallocate prepare statement;



        open cur_temp;

        fetch cur_temp into v_field;

        while (v_field is not null) do

                set v_result = concat(v_result, v_field, ',');

                fetch cur_temp into v_field;

        end while;

        close cur_temp;

        select v_result;



        drop view if exists view_temp_20150701;

end;



call p_simulate_dynamic_cursor();

        

 

使用temporary table

drop procedure if exists p_simulate_dynamic_cursor_by_temp_table;



create procedure p_simulate_dynamic_cursor_by_temp_table()

begin

    declare v_sql varchar(4000);

        declare v_field varchar(4000);

        declare v_result varchar(4000) default '';

        declare cur_temp cursor for select t.* from t_temp_20150701 t;

        declare continue handler for not found set v_field = null;



        set v_sql = 'create temporary table t_temp_20150701 as select t.id from t_user t limit 0, 100';

        

        set @v_sql = v_sql;

        prepare statement from @v_sql;

        execute statement;

        deallocate prepare statement;



        open cur_temp;

        fetch cur_temp into v_field;

        while (v_field is not null) do

                set v_result = concat(v_result, v_field, ',');

                fetch cur_temp into v_field;

        end while;

        close cur_temp;

        select v_result;



        drop temporary table if exists t_temp_20150701;

end;



call p_simulate_dynamic_cursor_by_temp_table();

 

你可能感兴趣的:(mysql)