Hi Geeks,
Welcome to the Part4 of SQL Server Cursor Operators. You can read previous posts by clicking Part1, Part2 and Part3.
In our previous posts, we have covered dynamic cursor operation but what happens if we change CURSOR type to STATIC, let’s see.
-- Database used in example is [AdventureWorks2012] -- Please click on Display Estimated Execution Plan icon 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
Entire execution plan is broken into 3 parts as shown above and we are going to discuss on the top most image which represents the cursor definition and remaining ones are same as dynamic cursor.
To start from the Top right, first operator is Clustered Index Scan to get data out of SalesTerritory table. This data is then passed to the Segment operator which divides the input into segments based on the columns and in our example it is based on derived column Segment1006. This derived column then split data and pass onto the next operator and then assign a unique key. Cursor operations requires work tables and for these tables to be efficient, SQL Server creates a clustered index with a unique key and in our static cursor, this key gets generated after segments are defined.
Next we see Sequence Project operator which adds new columns as part of computing set of data. In our example, this create row numbers through internal routine and they are used as identifiers within clustered index.
This data then passed to Clustered Index Insert and then Population Query cursor operator. This operator populates the work table for a cursor when it is opened. FETCH operation retrieves the rows from the CURSOR via Index Seek on the tempdb. Note, the Fetch Query operation is defined in a separate sequence as this cursor is static.
In the very end, Snapshot cursor operator representing a cursor that does not see any changes made by others.
Stay tuned, more to come on cursor operators. 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