Wednesday, 4 July 2018

MySQL Stored procedure to Generate-Extract Insert Statement

MySQL Stored procedure to Generate-Extract Insert Statement
A lot of places I saw people asking for ways to generate Insert statements.
We do have GUI Tools which can extract insert statements for us readily. of the time I choose the MySQLDump way to generate insert statements.
mysqldump -uroot -ppassword –complete-insert –no-create-info DATABASE TABLENAME > TABLENAME.sql
But mind is very unstable and hungry, we don’t stop at one solution.
So to remove my mind’s starvation for the Stored Procedure way to extract Insert statement I created following routine.
As you can see this is really a simple procedure revolves around Information_schema mainly to get details of any table and then fires the simple sql query.
The procedure I named: InsGen
Input parameters:
in_db: Database name of the table for which you want to generate insert statements
in_table: Tabel name
in_file: complete file path [eg: C:/mysqlInserts.sql or /var/lib/data/mysqlInserts.sql]
DELIMITER $$
DROP PROCEDURE IF EXISTS `InsGen` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsGen`(in_db varchar(20),in_table varchar(20),in_file varchar(100))
BEGIN
declare Whrs varchar(500);
declare Sels varchar(500);
declare Inserts varchar(2000);
declare tablename varchar(20);
set tablename=in_table;
select tablename;
# Comma separated column names – used for Select
select group_concat(concat(‘concat(\'”\’,’,’ifnull(‘,column_name,’,””)’,’,\'”\’)’)) INTO @Sels from information_schema.columns where table_schema=in_db and table_name=tablename;
# Comma separated column names – used for Group By
select group_concat(‘`’,column_name,’`’) INTO @Whrs from information_schema.columns where table_schema=in_db and table_name=tablename;
#Main Select Statement for fetching comma separated table values
set @Inserts=concat(“select concat(‘insert into “, in_db,”.”,tablename,” values(‘,concat_ws(‘,’,”,@Sels,”),’);’) from “, in_db,”.”,tablename,” group by “,@Whrs, ” INTO OUTFILE ‘”, in_file ,”‘”);
PREPARE Inserts FROM @Inserts;
EXECUTE Inserts;
END $$
DELIMITER ;
Sample output:
Generate Inserts mysql
I have not considered each and every scenarios yet, but this works for normal tables and it does error if file exists.

0 comments:

Post a Comment