Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
SQL

SQL Server: Why a Temp Table Inside a Stored Procedure Triggers Constant Recompilation

- 26.09.26 - ErcanOPAK

πŸ—„οΈ The Stored Procedure That Recompiles Itself Almost Every Time It Runs

A stored procedure that creates a `#temp` table, inserts a meaningful number of rows into it, and then queries it can trigger SQL Server’s automatic recompilation logic FAR more often than expected – because a significant enough change in a temp table’s row count between statements is one of the specific conditions SQL Server watches for to decide the cached execution plan might no longer be a good fit, and it silently recompiles rather than risk running a stale plan.

πŸ”Ž The Problem

CREATE PROCEDURE dbo.ProcessDailyOrders
AS
BEGIN
    CREATE TABLE #StagingOrders (OrderId INT, Total DECIMAL(10,2));

    INSERT INTO #StagingOrders
    SELECT OrderId, Total FROM Orders WHERE OrderDate = CAST(GETDATE() AS DATE);

    -- On a busy day, this INSERT can add thousands of rows to a table
    -- that started empty - a large enough jump in row count (governed by
    -- SQL Server'"'"'s internal recompilation thresholds) marks the cached
    -- plan for the queries below as stale, triggering a recompile on
    -- THIS query, and again on every subsequent query touching
    -- #StagingOrders in the same procedure, every single execution.
    SELECT * FROM #StagingOrders WHERE Total > 1000;
END

βœ… Fix: Reduce How Much the Temp Table’s Statistics Actually Change

  • `SELECT * FROM sys.dm_exec_query_stats` joined with `sys.dm_exec_sql_text`, or a Query Store recompile-reason report, confirms whether `#temp` table cardinality changes are actually the trigger here before spending time on a fix aimed at the wrong cause.
  • Adding `OPTION (RECOMPILE)` to the specific statement(s) touching the temp table can actually be the right call here – it accepts a small, predictable recompile cost on every execution in exchange for a plan tailored to the CURRENT row count, instead of an unpredictable recompile storm triggered by whatever threshold SQL Server hits.
  • Table variables (`DECLARE @StagingOrders TABLE (…)`) don’t trigger this specific automatic-recompilation behavior the way `#temp` tables do – though they come with their own tradeoff (no statistics at all, which can produce a poor plan for a large result set), so this swap is worth testing rather than assuming it’s a strict improvement.

⚠️ Why the Slowdown Looks Random From the Outside

  • The procedure runs identical logic every time, so a sudden slowdown with no code change looks like a mysterious performance regression – the actual trigger is data volume crossing an internal threshold, which has nothing to do with anything a developer directly controls in the query text.
  • This is worth checking specifically on procedures that behave inconsistently – fast on light days, slow on heavy ones – since that exact pattern (correlating with data volume rather than code changes) is a strong signal pointing at recompilation rather than a genuine query plan regression.

A temp table’s row count isn’t just data – to SQL Server’s optimizer, a big enough swing in it is a signal that the old plan for a query might not fit anymore.

β€” Database Engineer

Related posts:

Never Use SELECT * in Production β€” Here’s Why It Destroys Performance

How to insert results of a stored procedure into a temporary table

SQL: Use PRIMARY KEY and FOREIGN KEY for Data Integrity

Post Views: 3

Post navigation

The AI Prompt That Reviews Your Regex for Catastrophic Backtracking Before It Ships
ASP.NET Core: Fix a File Download That Arrives Corrupted Because of an Extra Buffering Step

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

October 2026
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Sep    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (951)
  • How to add default value for Entity Framework migrations for DateTime and Bool (939)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (836)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (624)
  • Add Constraint to SQL Table to ensure email contains @ (590)
  • Average of all values in a column that are not zero in SQL (553)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (526)
  • Find numbers with more than two decimal places in SQL (468)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps
  • Photoshop: Fix a Color Profile Mismatch That Makes Printed Output Look Nothing Like What You Saw On Screen
  • WordPress: Fix Search Results That Return Pages From a Theme You Deactivated Months Ago
  • Visual Studio: Fix a Test Project That Builds Fine Alone but Fails to Discover Any Tests After a NuGet Restore
  • ASP.NET Core: Fix a File Upload That Times Out on Slow Connections Only Because Kestrel’s Minimum Data Rate Feature Kicked In
  • JavaScript: Fix an Array Destructuring Default Value That Silently Never Applies Because null Was Passed Instead of Undefined

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (951)
  • How to add default value for Entity Framework migrations for DateTime and Bool (939)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (836)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com