Changetracking - Use tempDB to spill data

simon 61 Reputation points
2020-09-29T07:39:07.737+00:00

I 'm using sql changetracking to read changes on ax7.CPRPriceCPOStaging. Table has PK clustered key on 4 columns:

ALTER TABLE ax7.CPRPriceCPOStaging ADD CONSTRAINT [PK_Staging] PRIMARY KEY CLUSTERED ( [DATAAREAID] ASC, [PRODUCTVARIANTNUMBER] ASC, [VARIANTID] ASC, [FROMDATE] ASC )

So, I have this query:

SELECT ct.VariantID, ct.DATAAREAID, ct.FROMDATE, t.AMOUNT, t.[PRODUCTVARIANTNUMBER] FROM CHANGETABLE (CHANGES ax7.CPRPriceCPOStaging, 0) ct INNER JOIN ax7.CPRPriceCPOStaging t ON ct.DATAAREAID=t.DATAAREAID AND ct.[PRODUCTVARIANTNUMBER]=t.[PRODUCTVARIANTNUMBER] AND ct.VariantID=t.VARIANTID AND ct.FROMDATE=t.FROMDATE;

It is JOIN by clustered key. In query execution plan, after I read data from change tracking table, there is SORT operator at the end which sorts data by PK column order. It also creates spill to temp db and query is very slow. After that it perform index seek on "dbo.myTable", which is fine. How can I remove this sort from execution plan? Shouldn't be data from change_tracking table also sorted in the same order as PK is? Obviously not. How can I achieve that right sort order is returned from change tracking table or at least remove spill to temp db?

29062-executionplan.xml

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,321 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,524 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. EchoLiu-MSFT 14,571 Reputation points
    2020-09-30T06:58:37.593+00:00

    Hi @simon ,

    The following article may help you, please refer to:

    sp_BlitzCache™ Result: TempDB Spills
    How to avoid tempdb spill
    How to fix Tempdb spill warning and reduce the long running query timing?

    Best Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. simon 61 Reputation points
    2020-09-30T21:13:58.977+00:00

    Even if I do this query:

    SELECT ct.DATAAREAID INTO #tmp FROM CHANGETABLE (CHANGES ax7.CPRPriceCPOStaging, 269361) ct 
    

    I get "spill to temp db" warning.

    This reads data from change tracking generated table and i can't do anything about that, since this table is auto generated?