'Inserting rows per hour into another table

I have two tables, both have the same column structure. The first table has around 700 million rows. I want to copy these rows per hour into the second table.

To test my approach I've tried this query, which copies only one row from the first table into the second. The execution time for this query was around 4.5min

DECLARE @startDate DateTime2(0) = '2020-03-29 13:05:18'

DECLARE @endDate DateTime2(0) = '2020-03-29 13:05:18'

WHILE @startDate <= '2020-03-29 13:05:18'
BEGIN

SET @endDate = DATEADD(hh, 1, @startDate)

INSERT INTO "secondtable"

SELECT *
FROM "first table"
WHERE time_position >= @myCounter AND time_position <= '2020-03-29 13:05:18'

SET @startDate = DATEADD(hh, 1, @startDate)

END

For inserting rows per hour into the second table, I've tried this query but it's executing for 20+ minutes and the risk will probably run out of space and stop the query.

DECLARE @startTime DateTime2(0) = (select min(time_position) from "first table" where time_position = '2022-01-01')

DECLARE @endTime datetime2(0) = (select max(time_position) from "first table" where time_position = '2022-01-01')

WHILE @startTime <= @endTime 
BEGIN


INSERT INTO "second table"

SELECT *

FROM "first table"

WHERE time_position >= @startTime AND time_position <= @endTime

SET @startTime = DATEADD(HH, 1, @startTime)

END

How can I copy these rows per hour into the second table in an efficient way?

first table

second table

execution plan



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source