MySQL通过视图(或临时表)实现动态SQL(游标)
>参考de优秀文章
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();
作者:Nick Huang 博客:http://www.cnblogs.com/nick-huang/
本博客为学习、笔记之用,以笔记形式记录学习的知识与感悟。学习过程中可能参考各种资料,如觉文中表述过分引用,请务必告知,以便迅速处理。如有错漏,不吝赐教。
如果本文对您有用,点赞或评论哦;如果您喜欢我的文章,请点击关注我哦~
本博客为学习、笔记之用,以笔记形式记录学习的知识与感悟。学习过程中可能参考各种资料,如觉文中表述过分引用,请务必告知,以便迅速处理。如有错漏,不吝赐教。
如果本文对您有用,点赞或评论哦;如果您喜欢我的文章,请点击关注我哦~
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用