100, 10,000 and 1: How SQL Server Estimates Rows for Nested MSTVFs
The optimizer plans every statement with an estimate of how many rows it will process, the cardinality estimate. For a multi-statement table-valued function (MSTVF), it usually has nothing to base that estimate on and uses a fixed value instead. When functions call each other, this happens again at every level. Using a chain of three levels, this page shows which numbers the optimizer assumes where, how two fixed values turn into 10,000, when SQL Server actually counts the rows, and why table variables inside a function are sometimes planned with a single row. We tested the chain and the German version of the query on SQL Server 2017, 2019, 2022, and 2025, table variable deferred compilation, which exists only from 2019 on, on 2019, 2022, and 2025, and the English version of the query on 2017 CU31 and 2022 CU27.
In short
- Without interleaved execution, every MSTVF call is planned with 100 rows, or one row with the legacy cardinality estimator. This holds separately at each level of a chain: whatever is estimated inside the called function doesn’t reach the caller.
- A
CROSS APPLYover two MSTVFs yields 10,000. When a statement calls one MSTVF for each row of another MSTVF, the optimizer assumes 100 outer rows and 100 rows per inner call. This number appears only in the plan of the function body, never in the caller’s plan. - In our chain, interleaved execution applied only at the top. It applied to the direct call with a constant or a procedure parameter. It didn’t apply to the correlated
CROSS APPLY, and we observed it in none of the function bodies we tested, not even for read-only statements. - Table variables in statements that use the return table stay at one row. Starting with SQL Server 2019, the optimizer plans eligible statements with the row count of a table variable at their first execution. Inside an MSTVF, in our tests it estimated one row for every table variable in a statement that referenced the function’s return table.
The example: three levels
The synthetic shop from part 1, this time with a suitable index on the events table so that the access path doesn’t distract from the estimates. The chain returns each shipment of a customer that has events, together with its latest event:
- Level 3 returns the events of one shipment.
- Level 2 returns the shipments of one order and calls level 3 for each shipment.
- Level 1 returns the shipments of one customer. It gets the customer’s orders from another MSTVF and calls level 2 for each order.
-- Level 3 (innermost): events of one shipmentCREATE FUNCTION dbo.tvf_ShipmentEvents (@ShipmentId int)RETURNS @t TABLE (ShipmentId int NOT NULL, EventTime datetime2(0) NOT NULL, Status tinyint NOT NULL)ASBEGIN INSERT @t (ShipmentId, EventTime, Status) SELECT e.ShipmentId, e.EventTime, e.Status FROM dbo.ShipmentEvents AS e WHERE e.ShipmentId = @ShipmentId; RETURN;END;GO -- Level 2: shipments of one order with their latest eventCREATE FUNCTION dbo.tvf_OrderShipments (@OrderId int)RETURNS @t TABLE (OrderId int NOT NULL, ShipmentId int NOT NULL, LastEvent datetime2(0) NOT NULL, Status tinyint NOT NULL)ASBEGIN INSERT @t (OrderId, ShipmentId, LastEvent, Status) SELECT s.OrderId, s.ShipmentId, l.EventTime, l.Status FROM dbo.Shipments AS s CROSS APPLY (SELECT TOP (1) ev.EventTime, ev.Status FROM dbo.tvf_ShipmentEvents(s.ShipmentId) AS ev -- level 3 per shipment ORDER BY ev.EventTime DESC) AS l WHERE s.OrderId = @OrderId; RETURN;END;GO -- Helper function: orders of one customerCREATE FUNCTION dbo.tvf_CustomerOrders (@CustomerId int)RETURNS @t TABLE (OrderId int NOT NULL, OrderDate datetime2(0) NOT NULL)ASBEGIN INSERT @t (OrderId, OrderDate) SELECT o.OrderId, o.OrderDate FROM dbo.Orders AS o WHERE o.CustomerId = @CustomerId; RETURN;END;GO -- Level 1 (top): shipments of one customer, two MSTVFs in one statementCREATE FUNCTION dbo.tvf_CustomerShipments (@CustomerId int)RETURNS @t TABLE (OrderId int NOT NULL, ShipmentId int NOT NULL, LastEvent datetime2(0) NOT NULL, Status tinyint NOT NULL)ASBEGIN INSERT @t (OrderId, ShipmentId, LastEvent, Status) SELECT os.OrderId, os.ShipmentId, os.LastEvent, os.Status FROM dbo.tvf_CustomerOrders(@CustomerId) AS o CROSS APPLY dbo.tvf_OrderShipments(o.OrderId) AS os; -- level 2 per order RETURN;END;GO SELECT * FROM dbo.tvf_CustomerShipments(42);We called the chain for two customers: customer 42 with 5 orders and 7 shipments, and a large customer with 300 orders and 2,100 shipments. For the small customer, level 2 ran five times and level 3 seven times; for the large one, 300 and 2,100 times. A harmless-looking query thus triggers hundreds of function calls.
Level by level: what the optimizer assumes
Every MSTVF has its own plan, and every statement in it is planned separately. Where a statement calls an MSTVF, the plan shows a Table Valued Function operator, and the optimizer assumes 100 rows per execution for it. This is what we saw on all four versions:
| Where | What is planned | Estimated | Actual, averaged per execution (customer 42 / large customer) |
|---|---|---|---|
| Level 3 | Seek on the events of one shipment | 6 (statistics) | 6.6 / 3 |
| Level 2 | Seek on the shipments of one order | 1 (statistics) | 1.4 / 7 |
| Level 2 | Call of level 3 per shipment | 100 per call | 6.6 / 3 |
| Level 2 | Whole statement | 1 | 1.4 / 7 |
| Level 1 | Call of tvf_CustomerOrders | 100 | 5 / 300 |
| Level 1 | Call of level 2 per order | 100 per call | 1.4 / 7 |
| Level 1 | Whole statement | 10,000 | 7 / 2,100 |
| Caller | SELECT * FROM dbo.tvf_CustomerShipments(42) | 7, counted by interleaved execution | 7 |
Two things stand out. First, each level estimates on its own. The call of level 3 appears in level 2 with 100, although level 3 itself expects 6. In level 2, TOP (1) reins in the 100 again: the optimizer expects one shipment per order and at most one event per shipment, so one row. Second, the estimate is off in either direction depending on the customer: 100 orders are too many for customer 42 and too few for the large customer.
Where the 10,000 comes from
The 10,000 arises in level 1, in its single INSERT statement. There, the optimizer joins two function calls with Nested Loops: on the outer side tvf_CustomerOrders with 100 estimated rows, on the inner side tvf_OrderShipments with 100 rows for each of these outer rows. The join therefore shows 100 × 100 = 10,000. The optimizer plans everything above it with this number, in the lab a Table Spool and the insert into the return table. The actual result was 7 rows for customer 42 and 2,100 for the large customer. A further level below added no further factor of 100: level 1 uses the fixed 100 for the call of level 2, regardless of what level 2 estimates internally. So the 10,000 isn’t a rule for every kind of nesting, but the result of this one statement.
The caller’s plan doesn’t show the 10,000 anywhere. It only shows the top function operator with 100, or with the number that interleaved execution counted at compile time. The caller’s plan therefore shows only the outer estimate. For the large customer, it hides two errors in level 1: 100 estimated against 300 actual orders, and 10,000 estimated against 2,100 actual rows at the join.
If the table Orders takes the place of the outer function tvf_CustomerOrders in the statement, the optimizer estimates this part from statistics. In this variant of level 1, it calculated 5 orders (statistics) × 100 = 500. When the large customer came first, it was 300 × 100 = 30,000, and this plan stayed in the cache. How the first call shapes the plans inside a function is the subject of a separate part of this series.
With the legacy cardinality estimator (LEGACY_CARDINALITY_ESTIMATION = ON), the value is 1 instead of 100 everywhere, and the 10,000 becomes 1. Compatibility level 130 already uses the new estimator and assumes 100.
In this example, the wrong number had no effect on the access path: with the index, every access was a seek. Whether an estimate hurts depends on what the optimizer does with it, for example the type of a join or the size of a memory grant. A case in which a wrong estimate inside a function changes the access path follows in the section on table variables below.
Interleaved execution: in our chain only at the top
Starting with compatibility level 140, the optimizer can execute an MSTVF first, count its rows and plan the rest of the query with this number. Microsoft calls this interleaved execution. It is documented for compatibility level 140 and later, as long as it isn’t disabled, for read-only statements that aren’t part of a data modification, and only when the function is called with runtime constants. In the chain, it looked like this:
| Call of the top function | Interleaved execution | Estimated |
|---|---|---|
SELECT * FROM dbo.tvf_CustomerShipments(42) | yes | 7, i.e. correct |
the same in a procedure with parameter @CustomerId | yes | count of the first call |
FROM dbo.Customers AS c CROSS APPLY dbo.tvf_CustomerShipments(c.CustomerId) | no | 100 |
with OPTION (USE HINT('DISABLE_INTERLEAVED_EXECUTION_TVF')) | no | 100 |
| compatibility level 130 | no | 100 |
| all calls inside a function body | no | 100 |
The procedure parameter counts as a runtime constant. The count of the first call then stays in the plan: when customer 42 came first, the plan expected 7 rows for the large customer as well; the other way round, 2,100 for customer 42 too. In our ad hoc calls, by contrast, a different constant got its own plan and its own count. The basics are covered in T-SQL Functions.
Inside a function body, interleaved execution didn’t apply in any case. That was true for the calls in INSERT … SELECT, which Microsoft excludes as part of a data modification. But it was also true for purely read-only statements such as SELECT @n = COUNT(*) FROM dbo.tvf_CustomerOrders(@CustomerId), with the function parameter, with a local variable and even with the constant 42. The documentation says nothing about this. On SQL Server 2017, we had only the cached estimates and execution counters for the function body; the nested calls were estimated at 100 there as well. For the chain, this means: interleaved execution improves at most the number the caller plans with. Every level below it plans with 100.
With the legacy cardinality estimator, interleaved execution still ran; only the fixed values below it were 1 instead of 100.
The 1 inside the function: table variables in statements that use the return table
Up to SQL Server 2017, the optimizer plans table variables with one row by default, unless the statement runs with OPTION (RECOMPILE), because it doesn’t know at compile time how many rows they will hold. Starting with SQL Server 2019 (compatibility level 150), it defers the compilation of a statement that uses a table variable until its first execution and then plans with the actual row count, without distribution statistics. Microsoft calls this table variable deferred compilation.
Inside an MSTVF, it only partly applies. In our tests on SQL Server 2019, 2022, and 2025, a statement inside an MSTVF did not use deferred compilation as soon as it used the function’s return table. The optimizer then planned all table variables in this statement with one row, on the new compatibility levels as well. The cached plan showed TableCardinality="0" for them, whereas statements without the return table showed the row count of the first call. Microsoft doesn’t document this behavior.
The function from part 1 shows this, here in a database without a suitable index on the events table. On the left, the expensive step writes directly to the return table; on the right, it first writes to a local table variable:
The same latest status, once with a detour
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) -- target: return table 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 WHERE ev.ShipmentId = s.ShipmentId ORDER BY ev.EventTime DESC) AS e; RETURN;END;@s estimated at 1 row: Nested Loops, one scan per shipment, 2,000 scans for 2,000 shipments
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); DECLARE @r TABLE (ShipmentId int NOT NULL, Status tinyint NOT NULL, EventTime datetime2(0) NOT NULL); INSERT @s (ShipmentId) SELECT sh.ShipmentId FROM dbo.Shipments AS sh WHERE sh.OrderId = @OrderId; INSERT @r (ShipmentId, Status, EventTime) -- target: local table variable 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 WHERE ev.ShipmentId = s.ShipmentId ORDER BY ev.EventTime DESC) AS e; INSERT @t (ShipmentId, Status, EventTime) SELECT r.ShipmentId, r.Status, r.EventTime FROM @r AS r; RETURN;END;@s estimated with the rows of the first call: from about 20 shipments, Eager Index Spool, one scan
Code as used in the lab, SQL Server 2019, 2022 and 2025. Both versions return the same rows.
On the left, the optimizer plans with one shipment and chooses Nested Loops with one scan of the events table per shipment. On the right, it knows the number of shipments and places a temporary index (Eager Index Spool) under the Nested Loops; the events table is then read only once. The last statement on the right, the copy into the return table, stays at one row, but it only copies. In the cross-check with similar statements, both forms scanned once per shipment on compatibility level 140, i.e. without deferred compilation.
In our tests, “uses” covered more than just being the target of an INSERT:
| The return table appears in the statement … | Was compilation deferred? |
|---|---|
as the target of INSERT or UPDATE | no |
as a source, e.g. INSERT @local SELECT … FROM @t | no |
only in a subquery, e.g. WHERE NOT EXISTS (SELECT 1 FROM @t …) | no |
| not at all, the statement reads and writes only local table variables | yes, with the row count of the first execution |
If the return table appears, the single row applies to all table variables in the statement, including the local ones. The optimizer never planned the return table itself with its actual size, even when it already held thousands of rows.
It’s the return table, not table variables as a target. The same statements in a stored procedure or in a batch, with an ordinary table variable @t, used deferred compilation, except for the cross-check with the hint that disables it. And a wrong number doesn’t always hurt: in the test, a join with grouping got the same Hash Match with a single scan of the large table in both cases.
What helps
OPTION (RECOMPILE)on the expensive statement. It is then planned with the current row count on every call, even when it writes to the return table. In the lab, for 3 shipments the Nested Loops scanned the events table once per shipment; for 30 and 2,000 shipments, an Eager Index Spool on the inner side reduced that to one scan in total, regardless of the order of the calls. The price is one compilation per call, in a chain per function call.- The detour through a local table variable only helps if the first call is typical. Deferred compilation plans with the row count of the first execution and keeps that plan. When an order with 3 shipments came first in the lab, the optimizer chose Nested Loops without a spool and stuck with it. The following call with 2,000 shipments then scanned 2,000 times again, as without the detour. With about 20 or more shipments in the first call, the spool stayed. This threshold applies to our data, not in general.
- A suitable index changes the access path: with it, both function forms in part 1 accessed the events with an Index Seek.
- Rewriting as an inline function removes the fixed values and the table variables altogether. In the lab, the inline version of the chain estimated from statistics: just under 8 rows for customer 42 with 7 actual, about 450 for the large customer with 2,100 actual. That is off as well, but it depends on the customer and is visible in the caller’s plan.
You can disable deferred compilation with DEFERRED_COMPILATION_TV = OFF in the database, with compatibility level 140, or for one statement with OPTION (USE HINT('DISABLE_DEFERRED_COMPILATION_TV')). There is no switch that enables it for statements with the return table; there, OPTION (RECOMPILE) remains.
Query: MSTVF calls and their estimates
The following query searches the plans currently cached for the current database for the places where an MSTVF is called, in the caller as well as inside other functions. For each place, it shows the estimate, how often the statement ran and, on SQL Server 2019 and later, whether interleaved execution applied. Each row belongs to exactly one statement in the plan cache. To get there, the query fetches the plan of each statement of the database separately; @top_rows limits only the output, not this work.
Query: MSTVF calls in the plan cache
/* PSG · Nested MSTVFs · Query 2: MSTVF calls and their row estimates in the plan cache Multi-statement TVF calls and their row estimates, 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, database or server settings; it only sets session options (NOCOUNT, QUOTED_IDENTIFIER) and creates one temporary table in tempdb that is dropped at the end. It does, however, read statistics and text of every statement in the plan cache of the instance, fetches the statement plan of every statement of the current database and shreds the plans with a function operator with XQuery. @top_rows limits the output only, not this work; on a large or busy server this can use noticeable CPU and memory (early filter: @plan_handle). Run it at your own risk, on a test system or outside peak load first. Statement text from the plan cache 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); without it SQL Server raises a permission error (Msg 300). The login also needs metadata visibility for the called function (VIEW DEFINITION on the function, schema or database is sufficient); otherwise its row is omitted without a message. If only the caller is not visible, it appears as "module (name not visible)" with its object_id. - Scope: only plans currently in the cache, only statements that ran at least once since compilation, and only calls of multi-statement functions (sys.objects.type = 'TF') where both the compilation database and the function's database are the current database. Missing: cross-database calls (compiled in database A, target B.dbo.fn: neither in A nor in B), evicted plans, ad hoc plan stubs (optimize for ad hoc workloads) and inline functions (part of the caller's plan). Parameterized queries appear as "prepared". Statement plans that cannot be converted to xml (nested too deeply) are only counted (column note and a message). - Mapping: each row comes from one row of sys.dm_exec_query_stats (plan_handle and offsets) and its statement plan (sys.dm_exec_text_query_plan). Executions, text and position therefore belong to that statement. - estimated_rows: EstimateRows at the "Table-valued function" operator (per execution of the operator). estimated_rebinds / estimated_rewinds: EstimateRebinds / EstimateRewinds (inner side of a Nested Loops join: expected re-executions with changed or unchanged correlated values); estimated_executions = 1 + estimated_rebinds + estimated_rewinds. - interleaved_executed (SQL Server 2019 and later, last actual plan from sys.dm_exec_query_plan_stats, only for the rows returned): 1 = IsInterleavedExecuted set at the node; 0 = runtime counters at the node, attribute not set; NULL = no runtime data at the node (before 2019, no last plan; in our lab also for a function call in the condition of an IF). The cached plan itself does not contain this attribute. When a plan is reused, 1 can remain without a new count. With LAST_QUERY_PLAN_STATS = OFF mostly NULL, but not always: some function plans carry runtime counters even then (in our lab on 2022 and 2025). - statement_executions: execution_count of the statement since its compilation. Two function operators in the same statement show the same value: don't add them up. stmt_comp_id (StatementCompId of the statement in the plan; StatementId is always 1 in the statement plan) and node_id (NodeId of the operator) tell matching rows apart and link the row to the last actual plan. - @function_name, @caller_name: 'name' searches all schemas, 'schema.name' exactly this object. - One row per "Table-valued function" operator, statement and plan.*/SET NOCOUNT ON;SET QUOTED_IDENTIFIER ON; DECLARE @top_rows int = 50; -- number of rows, ordered by executionsDECLARE @function_name nvarchar(300) = NULL; -- NULL = all called functions, else 'name' or 'schema.name'DECLARE @caller_name nvarchar(300) = NULL; -- NULL = all callers, else 'name' or 'schema.name' of a moduleDECLARE @plan_handle varbinary(64) = NULL; -- NULL = all plans of the database, else this plan onlyDECLARE @text_length int = 200; -- characters of statement text DECLARE @f_name sysname = PARSENAME(@function_name, 1), @f_schema sysname = PARSENAME(@function_name, 2), @c_name sysname = PARSENAME(@caller_name, 1), @c_schema sysname = PARSENAME(@caller_name, 2); DROP TABLE IF EXISTS #psg_mstvf_calls;CREATE TABLE #psg_mstvf_calls ( plan_handle varbinary(64) NOT NULL, start_offset int NOT NULL, readable bit NOT NULL, statement_executions bigint NOT NULL, caller_type nvarchar(60) NULL, caller nvarchar(300) NULL, called_function nvarchar(300) NULL, stmt_comp_id int NULL, node_id int NULL, estimated_rows float NULL, estimated_rebinds float NULL, estimated_rewinds float NULL, statement_text nvarchar(max) NULL); -- 1. Fetch the statement plan of each statement of the current database; convert and shred only plans with a "Table-valued function" operatorWITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')INSERT #psg_mstvf_calls (plan_handle, start_offset, readable, statement_executions, caller_type, caller, called_function, stmt_comp_id, node_id, estimated_rows, estimated_rebinds, estimated_rewinds, statement_text)SELECT qs.plan_handle, qs.statement_start_offset, CASE WHEN k.x IS NULL THEN 0 ELSE 1 END, qs.execution_count, CASE WHEN cp.objtype = N'Adhoc' THEN N'ad hoc' WHEN cp.objtype = N'Prepared' THEN N'prepared' WHEN co.object_id IS NOT NULL THEN co.type_desc WHEN st.objectid IS NOT NULL THEN N'module (name not visible)' ELSE cp.objtype END, CASE WHEN cp.objtype IN (N'Adhoc', N'Prepared') THEN N'-' WHEN co.object_id IS NOT NULL THEN SCHEMA_NAME(co.schema_id) + N'.' + co.name ELSE CONCAT(N'object_id ', st.objectid) END, SCHEMA_NAME(fo.schema_id) + N'.' + fo.name, s.stmt.value(N'(@StatementCompId)[1]', N'int'), r.op.value(N'(@NodeId)[1]', N'int'), r.op.value(N'(@EstimateRows)[1]', N'float'), r.op.value(N'(@EstimateRebinds)[1]', N'float'), r.op.value(N'(@EstimateRewinds)[1]', N'float'), 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)FROM sys.dm_exec_query_stats AS qsINNER JOIN sys.dm_exec_cached_plans AS cp ON cp.plan_handle = qs.plan_handleCROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) AS stCROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, qs.statement_start_offset, qs.statement_end_offset) AS tqpCROSS APPLY (SELECT TRY_CONVERT(xml, tqp.query_plan) AS x) AS kOUTER APPLY k.x.nodes(N'/ShowPlanXML/BatchSequence/Batch/Statements/*') AS s(stmt)OUTER APPLY s.stmt.nodes(N'*[local-name() = "QueryPlan" or local-name() = "Condition" or local-name() = "CursorPlan"]//RelOp[@PhysicalOp = "Table-valued function"]') AS r(op)OUTER APPLY (SELECT r.op.value(N'(TableValuedFunction/Object/@Database)[1]', N'nvarchar(260)') AS fdb, r.op.value(N'(TableValuedFunction/Object/@Schema)[1]', N'nvarchar(260)') AS fsch, r.op.value(N'(TableValuedFunction/Object/@Table)[1]', N'nvarchar(260)') AS ftab) AS vLEFT JOIN sys.objects AS fo ON fo.type = 'TF' AND QUOTENAME(fo.name) = v.ftab AND QUOTENAME(SCHEMA_NAME(fo.schema_id)) = v.fsch AND QUOTENAME(DB_NAME()) = v.fdbLEFT JOIN sys.objects AS co ON co.object_id = st.objectidWHERE st.dbid = DB_ID() AND (@plan_handle IS NULL OR qs.plan_handle = @plan_handle) AND tqp.query_plan LIKE N'%PhysicalOp="Table-valued function"%' AND (k.x IS NULL OR fo.object_id IS NOT NULL) AND (@f_name IS NULL OR k.x IS NULL OR (fo.name = @f_name AND (@f_schema IS NULL OR SCHEMA_NAME(fo.schema_id) = @f_schema))) AND (@c_name IS NULL OR (co.name = @c_name AND (@c_schema IS NULL OR SCHEMA_NAME(co.schema_id) = @c_schema)))OPTION (MAXDOP 1); -- 2. Count statement plans that cannot be converted, keep only the top @top_rows rowsDECLARE @not_readable int = 0; SELECT @not_readable = COUNT(*) FROM #psg_mstvf_calls WHERE readable = 0OPTION (MAXDOP 1); DELETE FROM #psg_mstvf_calls WHERE readable = 0OPTION (MAXDOP 1); WITH r AS ( SELECT ROW_NUMBER() OVER (ORDER BY statement_executions DESC, caller, called_function, start_offset, node_id) AS rn FROM #psg_mstvf_calls)DELETE FROM r WHERE rn > @top_rowsOPTION (MAXDOP 1); IF @not_readable > 0 PRINT CONCAT(N'Note: ', @not_readable, N' statement plan(s) with a function operator not convertible to xml (nested too deeply), missing from the result.'); -- 3. Result; interleaved_executed from the last actual plan (SQL Server 2019 and later, dynamic so that the query runs on 2017)DECLARE @dmf_exists bit = 0;DECLARE @lqps nvarchar(20) = NULL; 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(400) = CONCAT(CASE WHEN @dmf_exists = 0 OR @lqps IS NULL THEN N'interleaved_executed not available before SQL Server 2019' WHEN @lqps IN (N'0', N'OFF') THEN N'LAST_QUERY_PLAN_STATS OFF: interleaved_executed mostly NULL' ELSE N'LAST_QUERY_PLAN_STATS ON' END, N'; statement plans not convertible to xml: ', @not_readable); -- CAST AS nvarchar(max): otherwise a concatenation is cut at 4,000 charactersDECLARE @ie_expression nvarchar(max) = CAST(CASE WHEN @dmf_exists = 1 THEN N'(SELECT CASE WHEN o.op.exist(N''RunTimeInformation/RunTimeCountersPerThread'') = 1 THEN ISNULL(o.op.value(N''(RunTimeInformation/RunTimeCountersPerThread/@IsInterleavedExecuted)[1]'', N''bit''), 0) END FROM sys.dm_exec_query_plan_stats(t.plan_handle) AS ps CROSS APPLY ps.query_plan.nodes(N''(//*[@StatementCompId = sql:column("t.stmt_comp_id")]/*[local-name() = "QueryPlan" or local-name() = "Condition" or local-name() = "CursorPlan"]//RelOp[@NodeId = sql:column("t.node_id")])[1]'') AS o(op))' ELSE N'CAST(NULL AS bit)' END AS nvarchar(max)); DECLARE @sql nvarchar(max) = CAST(N'' AS nvarchar(max)) + N'WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan'')SELECT t.caller_type, t.caller, t.called_function, t.estimated_rows, t.estimated_rebinds, t.estimated_rewinds, 1 + ISNULL(t.estimated_rebinds, 0) + ISNULL(t.estimated_rewinds, 0) AS estimated_executions, ' + @ie_expression + N' AS interleaved_executed, t.start_offset / 2 + 1 AS statement_start_char, t.statement_text, t.statement_executions, @note AS note, CONVERT(varchar(130), t.plan_handle, 1) AS plan_handle, t.stmt_comp_id, t.node_idFROM #psg_mstvf_calls AS tORDER BY t.statement_executions DESC, t.caller, t.called_function, t.start_offset, t.node_idOPTION (MAXDOP 1);'; EXEC sys.sp_executesql @sql, N'@note nvarchar(400)', @note = @note; DROP TABLE #psg_mstvf_calls;How to read the result:
- One row per function call and statement. A statement with two MSTVFs appears twice, like level 1 of the chain.
caller_typeandcallershow where the call is: in a function or procedure (with the object type as SQL Server records it), in an ad hoc query or in a prepared one, for example throughsp_executesql. estimated_rowsis the estimate per execution of the function operator. Without interleaved execution, it is 100, or 1 with the legacy estimator. Onlyinterleaved_executedtells you whether SQL Server counted: a counted number can also be 1 or 100.estimated_executionsis 1 plus the estimated repetitions (estimated_rebindsandestimated_rewinds). For a call on the inner side of aCROSS APPLY, the column shows how often the optimizer expects to execute the operator; on a rewind, it can reuse the previous result without running the function again. For the inner call in level 1 of the chain, that was 100, which together with 100 rows per execution makes the 10,000.statement_executionscounts how often the statement ran since it was compiled. If a statement contains two function calls, both rows carry the same value: don’t add them up. Many executions with an estimate of 100 are a candidate for a closer look.interleaved_executedcomes from the last actual plan and is available only on SQL Server 2019 and later. 1 means interleaved execution applied. With reused plans, the 1 can remain without a new count. 0 means runtime data is present, no count.NULLmeans no runtime data for this operator, for example before SQL Server 2019 or withoutLAST_QUERY_PLAN_STATS.- What’s missing: statements that haven’t run since compilation, evicted plans, cross-database calls and plans nested too deeply. The column
notecounts the latter. If your login can’t see a called function in the metadata, its row is omitted without a message;VIEW DEFINITIONon the functions is sufficient.
From the lab database on SQL Server 2019, after the calls of the chain (excerpt, columns shortened; German version of the query, values translated):
| caller_type | caller | called_function | estimated_rows | estimated_executions | interleaved_executed | statement_executions |
|---|---|---|---|---|---|---|
| SQL_TABLE_VALUED_FUNCTION | dbo.tvf_OrderShipments | dbo.tvf_ShipmentEvents | 100 | 1 | 0 | 650 |
| SQL_TABLE_VALUED_FUNCTION | dbo.tvf_CustomerShipments | dbo.tvf_CustomerOrders | 100 | 1 | 0 | 7 |
| SQL_TABLE_VALUED_FUNCTION | dbo.tvf_CustomerShipments | dbo.tvf_OrderShipments | 100 | 100 | 0 | 7 |
| SQL_STORED_PROCEDURE | dbo.pr_tvf_CustomerShipments | dbo.tvf_CustomerShipments | 7 | 1 | 1 | 2 |
| ad hoc | - | dbo.tvf_CustomerShipments | 7 | 1 | 1 | 1 |
| ad hoc | - | dbo.tvf_CustomerShipments | 100 | 1 | 0 | 1 |
The first row is level 2: its statement ran 650 times, and its cached plan estimates 100 rows per call of level 3. The second and third rows are the two calls in level 1, with 100 estimated executions for the inner one. The last row is the correlated call through CROSS APPLY, without interleaved execution.
How to proceed
- Make the chain visible. Which function calls which? The PSG Function Tree shows it.
- Look at the estimates of the calls. The query above shows where MSTVFs are planned with 100 or 1 row and how often the statements run. An inner call with many estimated executions, for example in a
CROSS APPLYover another MSTVF, points to a multiplication like the 10,000. - Don’t rely on the caller’s plan alone. Whether SQL Server counted at the top is shown by
interleaved_executed, not by a matching number: a fixed estimate can match by chance. And even when it counted at the top, every level below it in our chain planned with 100. - Check the expensive step inside the function. Invisible in the plan shows how to find it. If it uses the return table, the optimizer plans its table variables with one row. A suitable index,
OPTION (RECOMPILE)or a rewrite as an inline function then helps.
How we tested
We built the chain on SQL Server 2017 CU31, 2019 CU32, 2022 CU27, and 2025 CU10, each at the default compatibility level (140 to 170), plus compatibility level 130 and the legacy cardinality estimator on 2022, in Developer Edition on Linux. The basis was a shop schema with about two million shipment events, one small customer (5 orders, 7 shipments) and one large customer (300 orders, 2,100 shipments). We called the chain directly, correlated through CROSS APPLY, from a procedure and with the hint, in both orders of the customers, and after each call analyzed the cached plans of all levels, on 2019 and later also the last actual plans. The inline version returned the same rows.
We tested deferred compilation in a separate series on 2019, 2022, and 2025, with compatibility levels 150 to 170, with statements that use the return table as a target, as a source or in subqueries, and with the same statements in a procedure and a batch. The two versions of the status function and a third one with OPTION (RECOMPILE) ran in a database without the index, with orders of 3 to 2,000 shipments in varying order. Cross-checks: compatibility level 140, the option turned off, the hint. All versions showed the same picture. We didn’t collect timings.
Limits: synthetic schema, Linux rather than Windows, only simple statement forms, no large plan cache. We didn’t test MERGE, DELETE, cursors and loops inside the function body, table variables with additional indexes, or parallel plans. On SQL Server 2017, the last actual plan of the function body can’t be retrieved (sys.dm_exec_query_plan_stats arrived with 2019); there, we analyzed the cached estimates and the execution counters.
Sources
- Microsoft: Intelligent query processing: interleaved execution and table variable deferred compilation
- Erik Darling: Multi-Statement Functions
- Erik Darling: Table Variable Deferred Compilation Depth
More in this series: Back to the overview: Nested MSTVFs · Invisible in the plan · T-SQL Functions · PSG Function Tree