views:

48

answers:

2

Hello,

I need to create a script file with the Insert statements for the records I select in the mysql table.

For Instance, when i do Select * from emp where empid = 5, and say i get 10 records as result. Now I should create a script file with the insert statements of that 10 records to emp table.

I am using C# as code behind...

How?

A: 

Well now your question makes sense. You can do it within one query

INSERT INTO B.emp SELECT * FROM A.emp WHERE empid = 5
Col. Shrapnel
A: 
DELIMITER $$

DROP PROCEDURE IF EXISTS `sample`.`InsGen` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsGen`(
in_db varchar(20),
in_table varchar(20),
in_ColumnName varchar(20),
in_ColumnValue varchar(20)
)
BEGIN

declare Whrs varchar(500);
declare Sels varchar(500);
declare Inserts varchar(200);
declare tablename varchar(20);
declare ColName varchar(20);


set tablename=in_table;


# 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 IGNORE into ", in_db,".",tablename," values(',concat_ws(',',",@Sels,"),');')
 as MyColumn from ", in_db,".",tablename, " where ", in_ColumnName, " = " , in_ColumnValue, " group by ",@Whrs, ";");

 PREPARE Inserts FROM @Inserts;

EXECUTE Inserts;                    

END $$

DELIMITER ;
Anuya