>参考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();

最新文章

  1. 判别或预测方法汇总(判别分析、神经网络、支持向量机SVM等)
  2. 涵涵和爸爸习惯养成进度表(三)(June 25 - )
  3. [翻译]Autofac 解析服务
  4. dataguard集群搭建
  5. QC 2.0为啥可以快充
  6. cdoj 791 Frozen Rose-Heads
  7. Java线程安全相关概
  8. 精读《正则 ES2018》
  9. 简单了解Django
  10. intellij idea maven project 无法显示dependencies
  11. March 04th, 2018 Week 10th Sunday
  12. nginx+keeplived+tomcat
  13. Springboot学习06-Spring AOP封装接口自定义校验
  14. M2事后分析
  15. 有关O_APPEND标志和lseek()的使用
  16. Python Web学习笔记之socket编程
  17. 拼图游戏js
  18. Python 基础 json 与pickle
  19. krb5-libs这个RPM包删掉了导致ssh无法连接
  20. Egret入门(三)--创建HelloWorld项目(4.0-使用Egret Wing)

热门文章

  1. Wireshark基本介绍和TCP三次握手
  2. from VC的IDE使用技巧大全
  3. Linux系统中用stat命令查看文件的三个时间属性
  4. 【asp.net Core 2.0 初步探索】
  5. 通过配置CPU参数 worker_cpu_affinity 提升nginx性能
  6. C#编写的 8种初级+高级排序方法(转)
  7. tomcat使用方法大全
  8. Excel提示“此工作簿包含一个或多个无法更新的链接”怎么办
  9. bash 基本功能
  10. 命名管道FIFO和mkfifo函数