In MySQL, can I copy one row to insert into the same table?

后端 未结 26 2295
-上瘾入骨i
-上瘾入骨i 2020-11-27 09:56
insert into table select * from table where primarykey=1

I just want to copy one row to insert into the same table (i.e., I want to duplicate an ex

26条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 10:26

    This procedure assumes that:

    • you don't have _duplicate_temp_table
    • your primary key is int
    • you have access to create table

    Of course this is not perfect, but in certain (probably most) cases it will work.

    DELIMITER $$
    CREATE PROCEDURE DUPLICATE_ROW(copytable VARCHAR(255), primarykey VARCHAR(255), copyid INT, out newid INT)
    BEGIN
            DECLARE EXIT HANDLER FOR SQLEXCEPTION SET @error=1;
            SET @temptable = '_duplicate_temp_table';
            SET @sql_text = CONCAT('CREATE TABLE ', @temptable, ' LIKE ', copytable);
            PREPARE stmt FROM @sql_text;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;
            SET @sql_text = CONCAT('INSERT INTO ', @temptable, ' SELECT * FROM ', copytable, ' where ', primarykey,'=', copyid);
            PREPARE stmt FROM @sql_text;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;
            SET @sql_text = CONCAT('SELECT max(', primarykey, ')+1 FROM ', copytable, ' INTO @newid');
            PREPARE stmt FROM @sql_text;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;
            SET @sql_text = CONCAT('UPDATE ', @temptable, ' SET ', primarykey, '=@newid');
            PREPARE stmt FROM @sql_text;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;
            SET @sql_text = CONCAT('INSERT INTO ', copytable, ' SELECT * FROM ', @temptable, '');
            PREPARE stmt FROM @sql_text;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;
            SET @sql_text = CONCAT('DROP TABLE ', @temptable);
            PREPARE stmt FROM @sql_text;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;
            SELECT @newid INTO newid;
    END $$
    DELIMITER ;
    
    CALL DUPLICATE_ROW('table', 'primarykey', 1, @duplicate_id);
    SELECT @duplicate_id;
    

提交回复
热议问题