Hi Geeks,
Welcome to the Part3 of SQL Server Cursor Operator. If you missed my last two posts on the subject you can read them by clicking Part1 and Part2.
You might have noticed that in my last two posts on the subject, there is explicit instruction to click on Estimated Execution Plan Icon before running SQL statements used in the example. But why is that? The answer is actual execution plan doesn’t look as same as estimated plan, let’s see that.
-- Database used in example is [AdventureWorks2012] DECLARE TerritoryName CURSOR STATIC FOR SELECT SalesTerritory.Name FROM [Sales].[SalesTerritory] WHERE SalesTerritory.[Group] LIKE '%America%' OPEN TerritoryName FETCH NEXT FROM TerritoryName WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM TerritoryName END CLOSE TerritoryName DEALLOCATE TerritoryName
This plan will be repeated for each row of data added to the cursor. There are no cursor icons present in the plan and we can only observe a cursor command visible for FETCH CURSOR represented by T-SQL operator icon. The reason behind this is, all cursor operations are actual operations and FETCH is similar to SELECT statement used in SQL Server.
From this plan we can very easily understand why a dynamic cursor could be an expensive operation. You rightly guessed, it’s performing both a clustered index insert as well as reading all the reads required to return data to the cursor.
Stay tuned, we are going to continue cursor operators tomorrow.
Happy Learning!
Regards,
Kanchan
Like us on FaceBook | Join the fastest growing SQL Server group on FaceBook | Follow me on Twitter | Follow me on FaceBook