MySQL 5.5 中用户定义的表变量?
我最近从 MSSQL 迁移到 MySQL。
我想在 MySQL 5.5 存储例程中使用表变量(或等效变量)来填充在线报告的数据集。
在MS SQL中,我会这样做
...
...
DECLARE @tblName TABLE
WHILE <condition>
BEGIN
Insert Row based on iteration value
END
...
...
据我所知,我无法在MySQL中声明表变量(如果我错了请纠正我)如何在MySQL存储过程中实现上述逻辑?
I've recently moved from MSSQL to MySQL.
I would like to use a table variable (or equivalent) inside a MySQL 5.5 stored routine, to populate a dataset for an online report.
In MS SQL, I would do it this way
...
...
DECLARE @tblName TABLE
WHILE <condition>
BEGIN
Insert Row based on iteration value
END
...
...
From what I understand, I can't declare table variables in MySQL (correct me if I'm wrong) How do I implement the above logic in a MySQL stored procedure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以创建一个表或临时表并用您需要的数据填充它。
创建表语法
You could create a table or temporary table and populate it with data you need.
CREATE TABLE Syntax
您正确理解了该限制。 MySQL用户手册明确指出用户定义的变量不能引用表:
http://dev.mysql.com/doc/refman/5.5 /en/user-variables.html
You understand that limitation correctly. The MySQL user manual clearly states that user-defined variables cannot refer to a table:
http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
创建临时表tmp
(
id int 无符号不为空,
名称 varchar(32) 不为空
)
引擎=内存; -- 如果需要,更改引擎类型,例如 myisam/innodb
insert into tmp (id, name) select id, name from foo... ;
-- 做更多工作...
select * from tmp order by id;
如果存在 tmp,则删除临时表;
create temporary table tmp
(
id int unsigned not null,
name varchar(32) not null
)
engine=memory; -- change engine type if required e.g myisam/innodb
insert into tmp (id, name) select id, name from foo... ;
-- do more work...
select * from tmp order by id;
drop temporary table if exists tmp;
我认为这涵盖了它。另外,这个可能会有所帮助。
I think this covers it. Also, this may be helpful.