开发者

Is it possible to move a record from one table to another using a single SQL statement?

开发者 https://www.devze.com 2022-12-14 17:37 出处:网络
I need a query to move a record from one table to another开发者_JAVA技巧 without using multiple statements?No, you cannot move records in one SQL statement. You have to use an INSERT followed by a DEL

I need a query to move a record from one table to another开发者_JAVA技巧 without using multiple statements?


No, you cannot move records in one SQL statement. You have to use an INSERT followed by a DELETE statement. You should wrap these statements into a transaction, to make sure that the copy operation remains atomic.

START TRANSACTION;

INSERT INTO 
    new_table 
SELECT 
    *
FROM
    old_table
WHERE
    some_field = 'your_criteria';

DELETE FROM old_table WHERE some_field = 'your_criteria';

COMMIT;


If you really want to do this in a single SQL statement, one way to accomplish this would be to create an "after delete" trigger on the source table that inserts the row into the target table. This way you can move the row from the source table to the target table simply by deleting it from the source table. Of course this will only work if you want to insert into target table for every delete on the source table.

DELIMITER $$

DROP TRIGGER IF EXISTS TR_A_DEL_SOURCE_TABLE $$

CREATE TRIGGER TR_A_DEL_SOURCE_TABLE AFTER DELETE ON SOURCE_TABLE FOR EACH ROW BEGIN

  INSERT IGNORE INTO TARGET_TABLE(id,val1,val2) VALUES(old.id,old.va1,old.val2);

END $$

DELIMITER ;

So to move the row with id 42 from source table to target table:

delete from source_table where id = 42;


No - you might be able to do the INSERT in one nested statement, but you still need to remove the record.


There is no way to make it a single query, but if you HAVE to do it in a single query within an application you can create a Stored Procedure to do it for you.

DELIMITER $$

DROP PROCEDURE IF EXISTS `copydelete` $$
CREATE PROCEDURE `copydelete` (id INT)
BEGIN
INSERT INTO New_Table SELECT * from Old_Table WHERE Old_Table.IdField=id;
DELETE FROM Old_Table where IdField=id;
END $$

DELIMITER ;

Then you're new query is just

CALL copydelete(4);

Which will delete WHERE IdField=4;


Please note that the time delay between insert-select and delete can cause you to delete to much.

For a safe route you could use an update field:

update old_table set move_flag=1 where your_criteria
insert into ... select from ... where move_flag = 1
delete from old_table where move_flag=1

Or use a transaction which locks the old_table so no data can be added between insert... select and delete.

0

精彩评论

暂无评论...
验证码 换一张
取 消