MySQL通過視圖(或臨時表)實現動態SQL(游標)


>參考de優秀文章

寫MySQL存儲過程實現動態執行SQL

Dynamic cursor in stored procedure

 

MySQL通過視圖(或臨時表)實現動態SQL(游標)。

因在實現中,需要通過DDL語句創建視圖(或臨時表)、刪除視圖(或臨時表),故,只適合在一些一次性的腳本中使用,比如調試一些數據問題、做一些簡單的數據初始化。

不適合使用在涉及業務操作的程序中。

 

>使用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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM