I am trying to optimize a long transaction, and I have seen that the following is executed several times:
Declare @myCursor CURSOR FAST_FORWARD FOR SELECT field1, MIN(COALESCE(field2, -2)) FROM MyTable tempfact LEFT JOIN MyTable sd ON tempfact.ID = sd.ID AND sd.TransactionId = @transactionId WHERE tempfact.SomeField IS NULL AND tempfact.TransactionId = @transactionId GROUP BY tempfact.field1 OPEN @myCursor FETCH NEXT FROM @myCursor INTO @field1Variable, @field2Variable WHILE @@FETCH_STATUS = 0 BEGIN EXEC USP_SOME_PROC @field1Variable, @field2Variable FETCH NEXT FROM @myCursor INTO @field1Variable, @field2Variable END CLOSE @myCursor DEALLOCATE @myCursor
The code for USP_SOME_PROC sproc is as follows:
IF NOT EXISTS (SELECT * FROM SomeTable WHERE Field1 = @field1) BEGIN INSERT INTO SomeTable (Field1, Field2) VALUES (@field1, @field2) END
As I mentioned, this is done in quite a few places, tables and fields are related to each other, but the idea remains the same, and I'm sure there can be a way to increase the performance of these sprocs if the cursors are not and, possibly, by speeding up this transaction , the problem that we have with a dead end (topic for another message) can be solved.
source share