I need to insert a very large number of rows into a table from a query, which puts me at risk of exceeding space on tempdb
. I am in need of a solution that can avoid this issue, and am considering the use of cursors as a potential solution. Within each iteration of the cursor would be an insert query. My question is, would each insert query in a cursor have the potential to exceed space in tempdb
in the same way that a single insert would? Are the internal objects stored in tempdb
automatically cleaned out between each insert?
Note: I would do this testing myself, but our team for some reason only has access to the production server, and we have no access to the DBA tools that would allow me to monitor tempdb
. I do not want to risk exceeding space on production.
Original:
insert into dbo.Customer_Result
select
GroupID
, EndDate
, ActiveDate
, count(c.CUSTOMER_k),0) CustomerCount
, sum(Balance),0) TotalBalances
from dbo.Customer_Cohorts c
inner join dbo.Customer_Active_Flags a
on c.CUSTOMER_k = a.CUSTOMER_k
group by GroupID, EndDate, ActiveDate
Cursor solution:
declare @Cursor cursor
set @Cursor = cursor for select EndDate from dbo.EndDates
open @Cursor
fetch next from @Cursor
into @CohortDate
while @@fetch_status = 0
begin
insert into dbo.Customer_Result
select
GroupID
, EndDate
, ActiveDate
, count(c.CUSTOMER_k),0) CustomerCount
, sum(Balance),0) TotalBalances
from dbo.Customer_Cohorts c
inner join dbo.Customer_Active_Flags a
on c.CUSTOMER_k = a.CUSTOMER_k
where c.EndDate = @CohortDate
group by GroupID, EndDate, ActiveDate
-- are the internal objects stored in tempdb from the above insert automatically
-- cleaned out after the above insert is complete?
fetch next from @Cursor
into @CohortDate
end