Hi all.
Thanks for your time and expertise.
My question is about Table Spool operator
I have spent numerous hours reading all suggested topics, including topics when suggested during creation of this post.
The reason for Table Spool operator in query plan seems to be NOT an exact science but it's in the realm of magic.
I have a simple reproduction code to demonstrate an issue.
if you add Performance: Show Plan XML in profiler, then you will see something like this
I have appropriate indexes and queries are really simple.
I do not understand why this operator is there and is there any way to rid of it? I really would benefit from 44% gain.
Thank you.
use tempdb go BEGIN TRANSACTION --DROP TABLE dbo.OrderItems CREATE TABLE dbo.OrderItems ( itmID int NOT NULL ,itmIDInstance smallint NOT NULL ,itmIDParent int NULL ,itmIDParentInstance smallint NULL ,PRIMARY KEY (itmID, itmIDInstance) ) INSERT dbo.OrderItems VALUES (1, 1, NULL, NULL) ,(2, 1, 1, 1) CREATE INDEX IX ON dbo.OrderItems (itmIDParent, itmIDParentInstance) GO --DROP FUNCTION dbo.fnAPP_getOrderItems CREATE FUNCTION dbo.fnAPP_getOrderItems ( @itmID int ,@itmIDInstance smallint ) RETURNS @oriopr TABLE ( Lvl smallint NOT NULL ,itmID int NOT NULL ,itmIDInstance smallint NOT NULL ,PRIMARY KEY CLUSTERED ( Lvl ASC ,itmID ASC ,itmIDInstance ASC ) ) AS BEGIN; DECLARE @Lvl int = 0 INSERT @oriopr SELECT @Lvl as Lvl ,ori.itmID ,ori.itmIDInstance FROM dbo.OrderItems ori WHERE ori.itmID = @itmID AND ori.itmIDInstance = @itmIDInstance WHILE @@ROWCOUNT > 0 BEGIN SET @Lvl += 1 INSERT @oriopr SELECT @Lvl as Lvl ,ori.itmID ,ori.itmIDInstance FROM dbo.OrderItems ori -- this level items JOIN @oriopr r -- parents ON r.itmID = ori.itmIDParent AND r.itmIDInstance = ori.itmIDParentInstance WHERE r.Lvl = @Lvl - 1 END RETURN END GO SELECT * FROM dbo.fnAPP_getOrderItems (1, 1) ROLLBACK
Vladimir Moldovanenko