views:

83

answers:

2

I need a storedprocedure to get the records of a Table and return the value as Insert Statements for the selected records.

For Instance, The stored procedure should have three Input parameters...

1- Table Name

2- Column Name

3- Column Value

If

1- Table Name = "EMP"

2- Column Name = "EMPID"

3- Column Value = "15"

Then the output should be, select all the values of EMP where EMPID is 15 Once the values are selected for above condition, the stored procedure must return the script for inserting the selected values.

The purpose of this is to take backup of selected values. when the SP returns a value {Insert statements}, c# will just write them to a .sql file.

I have no idea about writing this SP, any samples of code is appreicated. Thanks..

+1  A: 

You can do this with mysqldump:

mysqldump --no-create-info --skip-triggers 
  --where="$COLUMN_NAME='$COLUMN_VALUE'" --databases $DB --tables $TABLE_NAME
Ike Walker
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