Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

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

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
SQL

SQL Server: Fix a Table-Valued Function Forcing a Row Scan

- 28.11.26 - ErcanOPAK

🗄️ Fix a Table-Valued Function Forcing a Row Scan

A multi-statement table-valued function’s body is opaque to SQL Server’s optimizer – it can’t see the SELECT and INSERT statements inside the function, so for cardinality estimation purposes it falls back to a fixed, low guess for how many rows the function will return, regardless of what the function actually does or how much data is behind it. That bad guess is exactly what feeds a nested loops join against the function, and a query that joins a large outer table against this kind of function can get priced as if every call returns a handful of rows, when in practice each call returns hundreds – turning what should be a simple set-based join into a plan shaped for a workload many times smaller than the real one.

🔎 The Problem

CREATE FUNCTION dbo.GetOrdersForRegion(@RegionId INT)
RETURNS @Result TABLE (OrderId INT, Total DECIMAL(10,2))
AS
BEGIN
    INSERT INTO @Result
    SELECT OrderId, Total FROM dbo.Orders WHERE RegionId = @RegionId;
    RETURN;
END
GO

SELECT c.CustomerName, o.OrderId, o.Total
FROM dbo.Customers c
CROSS APPLY dbo.GetOrdersForRegion(c.RegionId) o;

-- Actual execution plan:
-- Nested Loops (outer: Customers, ~50,000 rows)
--   -> Table-Valued Function [GetOrdersForRegion]
--      Estimated number of rows: 1        <- fixed MSTVF estimate
--      Actual number of rows: 340 (average, per call)
-- The optimizer priced this as 50,000 nested-loop iterations each
-- expected to touch ~1 row - the real workload is 50,000 iterations
-- each touching ~340 rows, over 17 million actual row accesses the
-- plan was never shaped to handle efficiently

✅ Fix: Make the Function Inline

  • Convert the function to an inline table-valued function, a single RETURN (SELECT …) with no BEGIN/END body, wherever the logic allows it – SQL Server expands an inline TVF directly into the surrounding query like a parameterized view, letting the optimizer estimate its actual row count instead of guessing.
  • On a recent compatibility level, check whether interleaved execution for multi-statement TVFs is active for this query – it lets the optimizer pause mid-compilation, actually run the function once, and use its real row count for the rest of the plan, which can remove this exact problem without rewriting the function at all.
  • If the function’s logic genuinely needs the procedural, multi-statement form, consider replacing the cross apply with a plain join against a view or inline TVF that captures the same filtering logic in a single settable, even if it means duplicating some logic rather than reusing the existing function.

🚨 Why This Is Dangerous

A query that joins against a multi-statement table-valued function can look completely reasonable in the T-SQL and still generate a catastrophically bad plan purely because of a fixed cardinality guess the optimizer has no way to improve on its own – and because the query itself hasn’t changed, this kind of regression often only shows up once the data behind the function grows past whatever size made the bad estimate harmless.

The optimizer doesn’t refuse to estimate a multi-statement function’s row count – it was simply never given a way to look inside and find out.

— Database Engineer

Related posts:

Why Your Index Exists But Is Never Used

Why Your Index Exists But Is Never Used

SQL Server: Fix an Orphaned User That Can't Log In After Restoring a Database to a New Server

SQL Server: Fix an Orphaned User That Can't Log In After Restoring a Database to a New Server

SQL Server: Fix a Columnstore Archive Compression Job Stalling

SQL Server: Fix a Columnstore Archive Compression Job Stalling

Views: 3
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Asp.Net Core: Fix Response Caching Ignoring a Vary Header
SQL Server: Fix a Natively Compiled Procedure Rejecting a Hint

Leave a Reply Cancel reply

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

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 562 views
Bits of .NET

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

Social

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