I have a query (not written myself) and I am trying to make it run faster. I have seem this SQL Query with Cursor optimization
Cannot see if the answer applies for my case. Is it possible to rewrite this query?
The structure is:
TRUNCATE TABLE TableA
declare @myvar as varchar(255)
declare cur CURSOR LOCAL FAST_FORWARD
for SELECT SUB_TRANS
FROM TableB
open cur
fetch next from cur
into @myvar
while @@FETCH_STATUS = 0
BEGIN
INSERT INTO TableA
SELECT many_thing
from 4_tables_with_join(Note: @myvar is included as a join condition)
fetch next from cur
into @myvar
END
close cur
deallocate cur
As a "general hint": you most likely don't need the cursor logic at all. I would recommend rewriting this as a straight insert ... select
query.
As pseudo-code, this would look like:
insert into tablea (col1, col2, ...)
select many_thing
from tableb tb
inner join ... -- use "tb.subtrans" here in the join conditions instead of "@myvar"