MySQL通过视图(或临时表)实现动态SQL(游标)
2015-07-02 11:36
573 查看
>参考de优秀文章
写MySQL存储过程实现动态执行SQLDynamic 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();
相关文章推荐
- MySQL分页技术、6种分页方法总结
- MySQL Cluster
- MySQL如何利用索引优化ORDER BY排序语句
- MySQL日志文件详解
- Mac安装MySQL
- MySQL错误代码大全
- MySQL数据库表名、列名、别名区分大小写的问题及解决
- MySQL学习笔记(二):内连接和外连接实现多表查询
- MySQL学习笔记(一):添加外键
- MySQL主从同步原理介绍
- Mysql插入空间数据
- mysql函数大全
- mysql 的权限体系介绍
- Another MySQL daemon already running with the same unix socket
- 解决mysql-5.6.14-winx64中文乱码问题
- Mysql的Merge存储引擎实现分表查询
- Windows下面安装和配置MySQL(5.6.20)
- mysql数据库目录存放位置更改
- mysql学习4:select,update,insert,delete
- mysql学习3:索引,触发器,试图