I have multiple table with primary key, data columns and batch no.
I require procedure which dynamically creates statement to copy rows from table and insert into same table by changing auto increment value batch no.
Original Table
mysql query should copy records of batch 1 and paste them as batch 10 as below
I have tried to write query but it is coping all records, also it gets failed timeout for large no of records.
CREATE PROCEDURE `duplicateRows`(_schemaName text, _tableName text, _omitColumns text, var_run_seq_no int,var_old_run_seq_no int)
BEGIN
SELECT IF(TRIM(_omitColumns) <> '', CONCAT('id', ',', TRIM(_omitColumns),'batch_no'), CONCAT('id',',batch_no')) INTO @omitColumns;
SELECT GROUP_CONCAT(COLUMN_NAME) FROM information_schema.columns
WHERE
table_schema = _schemaName
AND
table_name = _tableName
AND
FIND_IN_SET(COLUMN_NAME,@omitColumns) = 0
ORDER BY ORDINAL_POSITION INTO @columns;
SET @sql = CONCAT('INSERT INTO ', _tableName, '(', @columns, ',batch_no)',
'SELECT ', @columns, ',', var_batch_no,
' FROM ', _schemaName, '.', _tableName);
-- select @sql;
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;
END
Best Answer
Suppose we have the following table, containing test data as specified in your question. Notice that the id column is "AUTO_INCREMENTed". (MySQL version 5.7)
The following procedure may help you to find a solution that fits your purpose. Your initial idea - assembling a combination of an INSERT and a SELECT, and executing it - is still in there, just the method of finding all necessary columns is different.
Test
Notice: when using this procedure, you may encounter "gaps" in auto-incremented ID columns. More information about this:
https://dev.mysql.com/doc/refman/5.7/en/innodb-auto-increment-handling.html
https://stackoverflow.com/questions/29315012/what-if-auto-increment-gaps-caused-by-mysql-insert-on-duplicate-key-update
https://stackoverflow.com/questions/1841104/how-to-fill-in-the-holes-in-auto-incremenet-fields