I’m trying to optimize a long transaction and I’ve seen that the following is done quite a few 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 the 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
Like I mentioned this is done in quite a few places, tables and fields involved are different but the idea remains the same, and I’m sure that there might be a way to increase the performance of these sprocs if cursors are not used and probably by making this transaction faster an issue that we’re having with a deadlock (a subject for another post) might be solved.
You can use
MERGEfor this