Home > Database > Mysql Tutorial > body text

MySQL实现循环插入功能

WBOY
Release: 2016-06-07 17:16:45
Original
1318 people have browsed it

MySQL 不支持直接写SQL 语句实现循环插入功能. 想要实现该功能的方法有:用其他语言操控MySql或者用存储过程来实现两种。

MySQL 不支持直接写SQL 语句实现循环插入功能. 想要实现该功能的方法有:用其他语言操控MySql或者用存储过程来实现两种。

1、存储过程实现
A、表结构 (Create Table song)
------ ----------------------------------------------------------------------------------------
  CREATE TABLE `song` (
          `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Autoincreament element',
          `name` text NOT NULL,
          `datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          `rank` int(11) NOT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=8102001 DEFAULT CHARSET=gbk

B、定义存储过程
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`sp_insert_batch`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insert_batch`(IN number int(11))
BEGIN
  declare i int(11);
  set i = 1;
  -- such as 1-2000,2000-4000,....
  WHILE i     if mod(i,2000)=1 then
       set @sqltext =concat('(''',concat('t',i),''',''',now(),''',',ceil(10*rand()),')');
    elseif mod(i,2000)=0 then
       set @sqltext=concat(@sqltext,',(''',concat('t',i),''',''',now(),''',',ceil(10*rand()),')');
       set @sqltext=concat('insert into song (name,datetime,rank) values',@sqltext);
       prepare stmt from @sqltext;
       execute stmt;
       DEALLOCATE PREPARE stmt;
       set @sqltext='';
    else
       set @sqltext=concat(@sqltext,',(''',concat('t',i),''',''',now(),''',',ceil(10*rand()),')');
    end if;
    set i = i + 1;
  END WHILE;
  -- process when number is not be moded by 2000
  -- such as 2001,4002,15200,...
  if @sqltext'' then
     set @sqltext=concat('insert into song (name,datetime,rank) values',@sqltext);
     prepare stmt from @sqltext;
     execute stmt;
     DEALLOCATE PREPARE stmt;
     set @sqltext='';
  end if;
END$$
DELIMITER ;
C、调用存储过程
call sp_insert_batch (100); --参数为需要插入的行数

2、用其他语言操控MySql实现(以shell为例)
for ((i=1;ido `mysql test -e "insert into t1(idx,pw) value($i,md5($i));"`;
done

linux

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template