Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Cursor much faster when loop. What's wrong ?

$
0
0

Hello All!

I tried to modify script (not my) and this script contains the cursor inside:

SELECT TOP(100) * INTO #tmpTable FROM MyTable WHERE MyDate<@ThisDate

DECLARE My_Cursor CURSOR FOR SELECT ID, convert( varchar(max), MyRequest) AS MyResponse FROM #tmpTable WHERE ID > 0 AND MyNumber > 0 OPEN My_Cursor FETCH NEXT FROM My_Cursor INTO @ID, @Response WHILE @@FETCH_STATUS = 0 BEGIN

--Some T-SQL code

WHILE @MyVar <> 0 BEGIN --Some T-SQL code in loop with modification of @MyVar

END FETCH NEXT FROM MY_Cursor INTO @ID, @Response END CLOSE My_Cursor DEALLOCATE My_Cursor

I replaced this cursor on loop as follows:

SELECT TOP(100) *, ROW_NUMBER() OVER(ORDER BY MyRecord) AS '_Counter' INTO #tmpTable FROM MyTable WHERE MyDate < @ThisDate

DECLARE @cnt int SELECT @cnt = MAX(_Counter) FROM #tmpTable WHILE(@cnt >0) BEGIN SELECT @quid = QUID, @Response =convert(varchar(max),OFXRequest) FROM #tmpLog WHERE QUID > 0 AND OFXResSize > 0 AND _Counter = @cnt --Some T-SQL code WHILE @MyVar <> 0 BEGIN --Some T-SQL code in loop with modification @MyVar END SET @cnt = @cnt - 1 END

When I tested modified script without cursor - it worked 1 hour and 5 minutes. Script with cursor works 13 minutes.

Why script with cursor so much faster than without cursor ?
What's wrong in my code ?

Thanks

Andy


Andy Mishechkin


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>