mysql应用存储过程批量插入数据

时间:2021-10-31 09:58:43
--批量插入数据的sql语句
delimiter $$
DROP PROCEDURE IF EXISTS `test.sp_insert_batch` $$
CREATE DEFINER =`root`@`localhost` PROCEDURE `sp_insert_atch`(IN number INT)
BEGIN
DECLARE i INT ;
SET i = 1;
#such as 1-2000,2000-4000,
WHILE i <= number DO
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;
deallocate prepare stmt;
SET @sqltext='';
END IF;
END$$ delimiter ; CREATE TABLE `song`(
`id` INT NOT NULL AUTO_INCREMENT COMMENT 'Autoincrement element',
`name` TEXT NOT NULL ,
`datetime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`rank` INT NOT NULL ,
PRIMARY KEY (`id`)
) engine = MyISAM AUTO_INCREMENT = 8102001 DEFAULT CHARSET = gbk;

注:此存储过程,实际应用需要测试。