How to use the INSERT INTO SELECT statement for batch insertion
When you need to insert a large amount of data from one table to another, useINSERT INTO SELECT
Inserting statements in batches can improve efficiency. Batched inserts are implemented by breaking large insert operations into smaller batches, thereby reducing the stress on the database server.
Steps:
INSERT INTO SELECT
statement to insert data from the source table into the temporary table. Use theLIMIT
clause to limit the number of rows inserted at a time to create a batch.INSERT INTO #temp_table SELECT TOP (@batch_size) * FROM source_table WHERE NOT EXISTS (SELECT 1 FROM destination_table WHERE id = source_table.id);
INSERT INTO SELECT
statement again to insert data from the temporary table into the target table.INSERT INTO destination_table SELECT * FROM #temp_table;
DROP TABLE #temp_table;
Advantages:
Note:
IDENTITY_INSERT
option may cause primary key conflicts.The above is the detailed content of How to batch insert into select. For more information, please follow other related articles on the PHP Chinese website!