Heim  >  Artikel  >  Datenbank  >  Mysql使用小结:(1) 存储过程,循环,实现Mssql Server功能的exec_MySQL

Mysql使用小结:(1) 存储过程,循环,实现Mssql Server功能的exec_MySQL

WBOY
WBOYOriginal
2016-06-01 13:51:48949Durchsuche


最近开始总结自己学习的Mysql的经验,在这里跟大家分享。很希望大家很拍板砖,谢谢。

 

先说说,为什么我要学习Mysql的存储过程,因为Mysql在单纯的Script(脚本)里面,不支持循环。大家可以参考相关的文档。

 

先给出代码:

DELIMITER $$

DROP PROCEDURE IF EXISTS `dowhile` $$

CREATE PROCEDURE  `dowhile`()

DETERMINISTIC

BEGIN

  DECLARE v1 INT DEFAULT 1000;
  declare tablename varchar(10) default 'testTable';
  declare createString varchar(1000);

  while v1  0 DO
      set @nextTable = concat(tablename,v1);
      set createString = concat("create table `",@nextTable);
      set createString = concat(createString,"` ( `id` int null, `name` varchar(200) null); ");
      set @mytable = createString;
      select @mytable;
      PREPARE stmt_name FROM @mytable;
      EXECUTE stmt_name ;
      DEALLOCATE PREPARE stmt_name;

      set v1 = v1 -1;
  END while;

END$$

DELIMITER ;

 

 

第一步:建立一个Mysql存储过程,必须要注意的地方是:一定要使用 DELIMITER(定界符这个)关键字,否则会产生ErrorNum:1064。这点无论是使用命令行还是Mysql Tools(Workbench)都必须遵守。

具体参考:http://dev.mysql.com/doc/refman/5.1/en/stored-programs-defining.html ,又一次证明了,仔细阅读文档很重要。

更多参考:http://dev.mysql.com/doc/refman/5.1/en/stored-routines.html

 

第二步:使用循环,必须在Mysql存储过程中,希望Mysql新版本可以进行改进。

 

原文be used in the body of stored programs: Stored procedures and functions, triggers, and events. These objects are defined in terms of SQL code that is stored on the server for later invocation
 

 

具体参考:http://dev.mysql.com/doc/refman/5.1/en/sql-syntax-compound-statements.html

 

第三步:使用 PREPARE命令,打开一个Stmt,不要忘记关上。

具体参考:http://dev.mysql.com/doc/refman/5.1/en/sql-syntax-prepared-statements.html

 

 小结:

 

我这里使用循环,但是实际完成建表过程,只实现了300次。是不是在存储过程中,循环有限制?

探索1:循环限制,设置while循环最大循环数为100000,没有任何问题。时间:0.406秒 。(双核 2.47)

探索2:                                      循环数为10000000,没有任何问题。时间:27.753秒。

探索3:                                      循环数为20000000,没有任何问题。时间:48.578秒。

超过30秒的限制。

 

当超过10分钟之后,连接断开。主要分析,发现Workbench有一个自己的数据库连接时间,10分钟。

通过阅读发现了Mysql的超时设置是interactive_timeout = wait_timeout:28800s (480min) 6小时。

 

 

 

 

 

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn