Skill 1.2.3

Create table-valued functions

Key Concepts

An inline TVF consists of one RETURN (SELECT ...) statement. The optimizer expands it into the calling query like a parameterized view, so it uses the real statistics and indexes and performs well. A multi-statement TVF declares a return table variable, fills it with several statements and returns it; the optimizer has historically guessed its row count, although interleaved execution (compatibility level 140 and later) now uses the actual count for the rest of the plan.

TVFs are called in the FROM clause and are often combined with CROSS APPLY or OUTER APPLY to run once for each row of another table, for example to return the three latest orders of each customer. Inline TVFs are also the required form for Row-Level Security predicates, where they must be schema-bound.