SQL Server Cursor Operators – Part3

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

CursorActualExPlan

   

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

   

About Kanchan Bhattacharyya

Kanchan is an astute IT professional, a seasoned SQL Database Administrator with 13+ years of industry experience. A calculated risk taker with deep technical knowledge and has gained proficiency in database consulting and solutions across different environments. Kanchan holds MBA degree in IT and an International Executive MBA in Project Management. He is very passionate about SQL Server and holds MCSE (Data Platform), MCSA – SQL 2012, MCITP – SQL 2008 certifications. Currently he is focusing on cloud and latest releases of SQL Server. When not working, Kanchan likes to spend his time reading on new technical developments specifically on SQL Server and other related technologies.

View all posts by Kanchan Bhattacharyya →

Leave a Reply

Your email address will not be published.