Knowledge · Nested MSTVFs

Why MSTVF Statements Are Missing from the Actual Execution Plan

A query from the application is slow. You capture the actual execution plan, and it looks harmless: a few index seeks, a Nested Loops join, and a Table Valued Function operator with a few percent of the estimated cost. SET STATISTICS IO reports a handful of reads. None of this explains where the time goes.

Updated Nov 27, 2026 · approx. 14 min read

Topic Plan · Plan cache · LAST_QUERY_PLAN_STATSLab SQL Server 2017–2025
SCHEMATIC · WHAT THE TOOLS SHOWActual plancaller onlySELECTNested LoopsTable Valued Fncost: a few percentSTATISTICS IOno function bodyTable 'Orders' …Table '#B1C2D3E4' …Table 'ShipmentEvents'missingPlan cache · function bodydm_exec_query_statsINSERT @s … Shipmentsper orderINSERT @t … Scan ShipmentEventsper orderPlan and IO output don’t name the statement.The work sits in the function body.

If the query contains a multi-statement table-valued function (MSTVF), that’s no coincidence. The caller’s actual plan reveals at most that time is spent at the function operator, but not which statement inside the function uses it. STATISTICS IO reports the function’s return table but omits the base tables the function reads. The statements are recorded elsewhere, and you can retrieve them there. Using a small example, this page shows what the usual tools display, what they leave out and how to get the actual plan of the statements inside the function. We tested the behavior and the German version of the query on SQL Server 2017, 2019, 2022, and 2025, and also ran the English version of the query on 2017 CU31 and 2022 CU27.

In short

  • The actual plan shows only the caller. SET STATISTICS XML and “Include Actual Execution Plan” return exactly one plan, without the statements inside the function. The function operator does show the actual time, but neither the tables nor the reads inside the function. In the example, the estimated cost was 2.6% although the function did almost all of the work.
  • STATISTICS IO doesn’t list the tables inside the function. It reported only Orders from the caller’s query and the function’s return table. Shipments and the large events table that the function reads on every call were missing.
  • The estimated plan shows more. It contains the statements of the function body with their estimated cost. That gives you a quick first candidate for the expensive statement.
  • The actual numbers are in the plan cache. Each statement of the function has its own counters there. On SQL Server 2019 and later, sys.dm_exec_query_plan_stats can also return the last actual execution plan for the function as a whole.

The example

A small shop: orders, shipments and a large table of shipment events (pickup, delivery and so on) with around two million rows. A function returns the latest status of each shipment for an order. The events table has no index on ShipmentId.

We write the same logic twice: as a multi-statement function that first collects the shipments in a table variable, and as an inline function with a single query. Both return the same rows on all versions.

The same latest status, written twice

dbo.tvf_OrderStatus: two steps in table variables
CREATE FUNCTION dbo.tvf_OrderStatus (@OrderId int)RETURNS @t TABLE (ShipmentId int NOT NULL, Status tinyint NOT NULL,                  EventTime datetime2(0) NOT NULL)ASBEGIN    DECLARE @s TABLE (ShipmentId int NOT NULL PRIMARY KEY);     INSERT @s (ShipmentId)    SELECT sh.ShipmentId FROM dbo.Shipments AS sh WHERE sh.OrderId = @OrderId;     INSERT @t (ShipmentId, Status, EventTime)    SELECT s.ShipmentId, e.Status, e.EventTime    FROM @s AS s    CROSS APPLY (SELECT TOP (1) ev.Status, ev.EventTime                 FROM dbo.ShipmentEvents AS ev            -- this is where the work is                 WHERE ev.ShipmentId = s.ShipmentId                 ORDER BY ev.EventTime DESC) AS e;     RETURN;END;GO SELECT o.OrderId, o.OrderDate, s.ShipmentId, s.StatusFROM dbo.Orders AS oCROSS APPLY dbo.tvf_OrderStatus(o.OrderId) AS sWHERE o.CustomerId = 42;

In the caller’s actual plan: one Table Valued Function operator, estimated at 2.6% of the cost

dbo.itvf_OrderStatus: one query
CREATE FUNCTION dbo.itvf_OrderStatus (@OrderId int)RETURNS TABLEASRETURN    SELECT sh.ShipmentId, e.Status, e.EventTime    FROM dbo.Shipments AS sh    CROSS APPLY (SELECT TOP (1) ev.Status, ev.EventTime                 FROM dbo.ShipmentEvents AS ev            -- visible in the plan                 WHERE ev.ShipmentId = sh.ShipmentId                 ORDER BY ev.EventTime DESC) AS e    WHERE sh.OrderId = @OrderId;GO SELECT o.OrderId, o.OrderDate, s.ShipmentId, s.StatusFROM dbo.Orders AS oCROSS APPLY dbo.itvf_OrderStatus(o.OrderId) AS sWHERE o.CustomerId = 42;

In the caller’s actual plan: Clustered Index Scan on ShipmentEvents, estimated at around 80% of the cost

Code as used in the lab. Both functions are called for the five orders of one customer.

Without a suitable index, both variants scanned ShipmentEvents once per shipment and read practically the same amount in total, albeit with different plans. What differs most is what you get to see of it.

What the actual plan shows

With SET STATISTICS XML ON or “Include Actual Execution Plan” in SSMS, SQL Server returns exactly one plan with exactly one statement for the call to the multi-statement function: the caller’s query. The two INSERT statements from the function are missing, on the first call with an empty plan cache as well as on the second.

In the plan, the function appears as a “Table Valued Function” operator:

  • Estimated cost: 2.6% of the caller’s estimated cost. When planning the caller, the optimizer doesn’t know the function body and uses a flat value.
  • Actual time: In the operator’s properties (Actual Time Statistics), it matched practically the runtime of the whole query. So this is where a look into the function pays off. The reads at the operator, on the other hand, cover only the return table.
  • Rows: estimated at 100 per call, so 500 for five orders. Actually, 7 came back. The cardinality estimator in SQL Server 2014 and later uses this fixed guess when interleaved execution doesn’t apply; the legacy estimator assumes one row.
  • What’s missing: which statement inside the function uses the time, any hint of ShipmentEvents, and that the scan runs again for every shipment.

From compatibility level 140, interleaved execution can pause optimization for suitable read-only queries, run the function and continue planning with the actual row count. In the lab it applied to a direct call with a constant parameter (SELECT * FROM dbo.tvf_OrderStatus(2)), on 2017 as well, but not to the correlated CROSS APPLY of the example. It doesn’t change the picture: even for the direct call, the actual plan shows only the caller, just with the right row count.

The inline variant, in contrast, shows everything. Its plan contains the Clustered Index Scan on ShipmentEvents with seven executions, and this scan accounts for an estimated 80% or so of the cost (around 77% on SQL Server 2017, with a slightly different plan shape). Anyone who sees this plan knows right away where to look.

What STATISTICS IO reports

For many people, SET STATISTICS IO ON is the first tool to reach for: it shows how many logical reads SQL Server reports for each table. For the multi-statement function, SQL Server reported only two entries on all four versions:

  • the Orders table from the caller’s query,
  • a temporary table with a generated name such as #B1C2D3E4: the function’s return table, with one scan per call.

ShipmentEvents doesn’t appear, and neither does Shipments. The reads of the statements inside the function are not shown in this output. That they still happen is shown by the plan cache and by the session’s read counter: in both variants, the query read practically the same amount there.

For the inline variant, STATISTICS IO reports the events table with seven scans and most of the reads, as you would expect.

This is our own observation; Microsoft’s documentation on SET STATISTICS IO doesn’t mention functions. We didn’t test nested multi-statement functions here. In practice, this means an unremarkable STATISTICS IO output doesn’t clear a query with a multi-statement function. A small temporary table with a generated name is a hint that a function with a return table is involved. Whether it’s an MSTVF is shown by sys.objects with type TF.

The estimated plan shows more

Here the usual rule is turned around. The estimated plan (SET SHOWPLAN_XML ON or “Display Estimated Execution Plan”) contains not only the caller’s query but also the statements of the function body, each with its own plan and cost. SSMS displays them as additional queries in the same batch.

In the example there were four statements: the caller, the function’s two INSERT statements and its RETURN. The second INSERT contained the Clustered Index Scan on ShipmentEvents with an estimated 90.7% of that statement’s estimated cost. Relative to the whole batch, the caller’s query dropped to a fraction of a percent.

A first hint of the expensive statement here is the scan in the second INSERT. Two limitations remain:

  • These are estimates. The estimated plan doesn’t show how often the statement actually runs. Here it ran once per order, i.e. for every row from Orders.
  • The costs of the function and the caller don’t add up. In the caller’s plan, the function still shows 2.6%. Both figures come from separate estimates and can’t be combined.

Where the actual numbers are: the plan cache

A multi-statement function has its own cached plan, similar to a stored procedure. sys.dm_exec_cached_plans lists it as Proc with Compiled Plan. The inline function has no plan of its own: it appears there only as View with Parse Tree, because its code is built into the caller’s plan.

As a result, the function’s statements have their own counters in sys.dm_exec_query_stats. Using sys.dm_exec_sql_text and the objectid column, you can attribute them to the function. In the lab we ran the query three times, each time for five orders. Afterwards, sys.dm_exec_query_stats contained exactly the function’s two INSERT statements with 15 executions each: one per order and call. The second statement accounted for practically all reads.

Two places you would look stay empty:

  • sys.dm_exec_function_stats has no row for the multi-statement function. This view lists scalar functions only.
  • sys.dm_exec_procedure_stats doesn’t contain it either, although the cached plan is listed as Proc.

The following query brings this together. By default, it returns the top 50 cached statements of multi-statement functions in the current database, ranked by total logical reads.

Query: Statements inside multi-statement functions

Query 1: Statements inside multi-statement functions · read-only · tested on SQL Server 2017–2025
/* PSG · Nested MSTVFs · Query 1: Statements inside multi-statement functions   Statements inside multi-statement table-valued functions, from the plan cache   As of Nov 27, 2026 · German version tested on SQL Server 2017 CU31, 2019 CU32, 2022 CU27, 2025 CU10;   this English version run on 2017 CU31 and 2022 CU27    WARNING: Read-only (plan cache DMVs), changes no data, objects or settings. It does scan the whole plan cache of   the instance and can use noticeable resources on a busy server. Run it at your own risk, on a test system or   outside peak load first. The plan cache holds statement text that may contain confidential values: review the   output before you share it.    - Run it in the database that contains the functions. Permissions: VIEW SERVER STATE (2017/2019) or     VIEW SERVER PERFORMANCE STATE (2022 and later). The login also needs metadata visibility for the     functions; VIEW DEFINITION on the function (or schema, database) is sufficient. Functions the     login cannot see are omitted without an error.   - Shows only statements whose plan is currently cached. Inline functions don't appear:     they are part of their caller's plan.   - Column last_plan: SQL Server 2019 and later, from sys.dm_exec_query_plan_stats. Complete with     runtime values only if LAST_QUERY_PLAN_STATS was on in the database (or trace flag 2451) when the     function ran. Switching it on cleared the database's plan cache in our lab.     The plan covers the whole function, so it repeats in each of its rows.   - One row per statement and plan: if a function has several cached plans, it appears several times.*/SET NOCOUNT ON; DECLARE @function_name sysname = NULL;   -- NULL = all multi-statement functions, else the name without schemaDECLARE @top_rows      int     = 50;     -- number of rows, ordered by logical readsDECLARE @text_length   int     = 200;    -- characters of statement textDECLARE @with_plan     bit     = 1;      -- 1 = include the last actual plan (if available) DECLARE @dmf_exists bit = 0;DECLARE @lqps       nvarchar(20) = NULL;   -- NULL = option unknown (SQL Server 2017) SELECT @dmf_exists = 1 FROM sys.all_objectsWHERE name = N'dm_exec_query_plan_stats' AND schema_id = SCHEMA_ID(N'sys')OPTION (MAXDOP 1); SELECT @lqps = CONVERT(nvarchar(20), value) FROM sys.database_scoped_configurationsWHERE name = N'LAST_QUERY_PLAN_STATS'OPTION (MAXDOP 1); DECLARE @note nvarchar(300) = CASE    WHEN @dmf_exists = 0 OR @lqps IS NULL        THEN N'LAST_QUERY_PLAN_STATS not available (before SQL Server 2019)'    WHEN @lqps IN (N'0', N'OFF')        THEN N'Database option OFF: last_plan may be incomplete; complete with the option ON or trace flag 2451'    ELSE N'Database option ON: last actual plan in column last_plan'    END; DECLARE @plan_expression nvarchar(400) = CASE    WHEN @with_plan = 1 AND @dmf_exists = 1        THEN N'(SELECT ps.query_plan FROM sys.dm_exec_query_plan_stats(qs.plan_handle) AS ps)'    ELSE N'CAST(NULL AS xml)' END; DECLARE @sql nvarchar(max) = N'SELECT TOP (@top_rows)       SCHEMA_NAME(o.schema_id) + N''.'' + o.name                                   AS function_name,       qs.statement_start_offset / 2 + 1                                           AS statement_start_char,       LEFT(LTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(st.text, qs.statement_start_offset / 2 + 1,            (CASE WHEN qs.statement_end_offset = -1 THEN DATALENGTH(st.text) ELSE qs.statement_end_offset END             - qs.statement_start_offset) / 2 + 1), NCHAR(13), N'' ''), NCHAR(10), N'' ''), NCHAR(9), N'' '')), @text_length) AS statement_text,       qs.execution_count                                                          AS executions,       qs.total_logical_reads                                                      AS logical_reads_total,       qs.total_logical_reads / NULLIF(qs.execution_count, 0)                      AS logical_reads_per_execution,       qs.last_execution_time                                                      AS last_execution,       qs.creation_time                                                            AS plan_created,       CONVERT(varchar(130), qs.plan_handle, 1)                                    AS plan_handle,       @note                                                                       AS last_plan_note,       ' + @plan_expression + N'                                                   AS last_planFROM sys.dm_exec_query_stats AS qsCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS stINNER JOIN sys.objects AS o ON o.object_id = st.objectid AND o.type = ''TF''WHERE st.dbid = DB_ID()  AND (@function_name IS NULL OR o.name = @function_name)ORDER BY qs.total_logical_reads DESC, o.name, qs.statement_start_offsetOPTION (MAXDOP 1);'; EXEC sys.sp_executesql @sql,     N'@top_rows int, @function_name sysname, @text_length int, @note nvarchar(300)',     @top_rows = @top_rows, @function_name = @function_name, @text_length = @text_length, @note = @note;

How to read the result:

  • One row per statement and plan in the function body, with the function name, the start of the statement text and the plan_handle. If the same function has several cached plans, for example because applications use different SET options, it appears several times. Inline functions don’t appear; their work belongs to the caller.
  • executions counts how often the statement ran since the plan was cached. For a function that is called once per row, this is a multiple of the calls from the application.
  • Reads: The total, by which the list is sorted, shows which statement read the most during the period covered. The value per execution together with the number of executions shows whether a single run reads a lot or many small ones add up. If a statement reads far more per execution than its result suggests, it’s the first candidate for a look at its access path.
  • last_plan contains, from SQL Server 2019, the function’s last plan from sys.dm_exec_query_plan_stats. It is complete with runtime values only if LAST_QUERY_PLAN_STATS was on in the database, or trace flag 2451 on the server, when the function ran. Without either, SQL Server 2019 returned only a plan skeleton in the lab, and 2022 and 2025 returned runtime values for only some of the statements. The last_plan_note column states the database option’s setting. On SQL Server 2017, last_plan stays empty.
  • Empty list: The function’s plan isn’t (or is no longer) cached, for example after a restart; you’re in the wrong database; or you can’t see the function in the metadata. VIEW DEFINITION on the function is sufficient. Functions you can’t see are omitted without an error message.

From the lab database, after three runs of the example query (columns shortened):

function_namestatement_textexecutions
dbo.tvf_OrderStatusINSERT @t (ShipmentId, Status, EventTime) SELECT s.ShipmentId, e.Status, e.EventTime FROM @s AS s CROSS APPLY (SELECT TOP (1) …15
dbo.tvf_OrderStatusINSERT @s (ShipmentId) SELECT sh.ShipmentId FROM dbo.Shipments AS sh WHERE sh.OrderId = @OrderId15

Getting the actual plan of the function body

From SQL Server 2019, SQL Server can keep the counters of the last execution for every cached plan. This also applies to the plan of a multi-statement function. Here is how to get the actual plan of its statements:

Step 1: Check the setting and switch it on if needed. In the function’s database, and only after agreement. If the option is already 1, leave it as it is. In the lab, switching it on cleared the database’s plan cache: all of its queries are recompiled afterwards.

SELECT value AS last_query_plan_statsFROM sys.database_scoped_configurationsWHERE name = N'LAST_QUERY_PLAN_STATS'; -- Only if value = 0:ALTER DATABASE SCOPED CONFIGURATION SET LAST_QUERY_PLAN_STATS = ON;

Step 2: Run the slow query once, the way the application does.

Step 3: Retrieve the function’s last actual plan. This is read-only. You need the same permissions as for the query above, including VIEW DEFINITION on the function. You get one row per plan of the function, the most recently used first; if SSMS and the application call it with different SET options, there are two.

SELECT OBJECT_NAME(st.objectid, st.dbid) AS function_name,       h.plan_handle,       h.last_execution,       ps.query_plan                     AS last_actual_planFROM (SELECT qs.plan_handle, qs.sql_handle,             MAX(qs.last_execution_time) AS last_execution      FROM sys.dm_exec_query_stats AS qs      GROUP BY qs.plan_handle, qs.sql_handle) AS hCROSS APPLY sys.dm_exec_sql_text(h.sql_handle) AS stCROSS APPLY sys.dm_exec_query_plan_stats(h.plan_handle) AS psWHERE st.objectid = OBJECT_ID(N'dbo.tvf_OrderStatus')  AND st.dbid = DB_ID()ORDER BY h.last_execution DESCOPTION (MAXDOP 1);

Step 4: If you switched the option on yourself in step 1, switch it off again afterwards: ALTER DATABASE SCOPED CONFIGURATION SET LAST_QUERY_PLAN_STATS = OFF;

The result is the whole function body as one plan: both INSERT statements with actual rows and executions per operator. In the example, it showed the Clustered Index Scan on ShipmentEvents with its actual rows, and after creating a suitable index an Index Seek instead. Clicking the XML opens the plan in SSMS.

Three things to know:

  • It’s the last execution of this plan, not the last query. If the function is called once per row, the plan shows only the last of these calls, in the example the fifth order with one execution per operator. It doesn’t add up all calls of a query. If another session has called the function in the meantime, you see that execution. For totals, use sys.dm_exec_query_stats.
  • The option has a cost. How much, and when to take a closer look first, is covered in The last actual plan. In a production database, switch it on only after agreement and for a specific purpose.
  • This route doesn’t exist on SQL Server 2017. Both the database option and sys.dm_exec_query_plan_stats are missing there, even with trace flag 2451. What remains are the estimated plan and the counters from the plan cache.

What about Query Store?

Query Store records the function’s statements as separate queries with the function’s object_id, separate from the caller. We tested with QUERY_CAPTURE_MODE set to ALL, the default on SQL Server 2017. Starting with SQL Server 2019, the default is AUTO, and rarely run statements can be missing. We didn’t test how function statements behave under AUTO. This is useful for tracking the expensive statement over a longer period. One trap remains: the counters of the caller and of the function’s statements overlap. In the lab, both counted almost the same reads. If you add up all queries in a database, you count the function’s work twice, and more often in a chain. So evaluate the caller and the function’s statements separately. More on this in Where does the time go?.

The index doesn’t change the caller’s plan

We then added an index and compared the plans again. With a suitable index ShipmentEvents (ShipmentId, EventTime DESC) INCLUDE (Status), the scan becomes a seek in both variants. With the inline function, you see it immediately: the caller’s estimated cost drops to a fraction, and the plan shows the Index Seek.

With the multi-statement function, the caller’s plan stays the same: the same operators, the same estimated cost, again 2.6% for the function. Only the plan of the function body has changed. If you judge the success of a change by the caller’s plan, you see neither the problem nor the solution with an MSTVF.

How to proceed

  1. Recognize the function. If the plan shows “Table Valued Function” with a lot of actual time and STATISTICS IO lists a small temporary table with a generated name, a multi-statement function is probably involved. sys.objects (type TF) tells you for sure.
  2. Look at the estimated plan. It shows the statements of the function body with their estimated cost and thus a first candidate.
  3. Get the actual numbers. The query shows how often each statement ran and how much it read.
  4. Retrieve the last actual plan if needed. From SQL Server 2019 with LAST_QUERY_PLAN_STATS, targeted and for a limited time.
  5. Check the access path, then the form. How to continue with a chain of several functions is shown in the series overview.

How we tested

We built the example on SQL Server 2017 CU31, 2019 CU32, 2022 CU27 and 2025 CU10, each at the version’s default compatibility level (140 to 170), in Developer Edition on Linux. The data was identical on all versions: around two million shipment events, one customer with five orders and seven shipments. We captured estimated and actual plans of the example query, compared STATISTICS IO with the session’s read counter, and evaluated the plan cache, Query Store and the last actual plan, each without and with a suitable index. Both functions returned the same seven rows in all cases. We evaluated plans as XML, not in SSMS’s graphical view. We didn’t evaluate runtimes for the comparison.

Limits: one schema and one call pattern, warm cache, no load. We didn’t test whether STATISTICS IO behaves the same for scalar functions or nested multi-statement functions, nor the legacy cardinality estimator.

Sources

More in this series: Back to the overview: Nested MSTVFs · Row estimates in the chain · T-SQL Functions · The last actual plan · PSG Function Tree

More in this series