Inline Table-Valued Functions (TVFs) in MS-SQL Server Part-1

Опубликовано: 24 Март 2026
на канале: QueryMastery
20
1

Inline Table-Valued Functions (TVFs) in SQL Server are a type of user-defined function that returns a table data type and is often used to encapsulate a query to be reused multiple times with different parameters. Unlike multi-statement table-valued functions, inline TVFs are more efficient as they are essentially parameterized views and do not require the creation of intermediate tables.

Here is a detailed explanation of inline TVFs in SQL Server, including how to create and use them:

Creating an Inline Table-Valued Function
To create an inline table-valued function, you use the CREATE FUNCTION statement. Here’s the syntax:

CREATE FUNCTION function_name (@parameter1 datatype, @parameter2 datatype, ...)
RETURNS TABLE
AS
RETURN
(
SELECT column1, column2, ...
FROM table_name
WHERE condition
);

Example
Suppose we have a table called Sales with the following columns: SaleID, ProductID, SaleDate, Amount, and we want to create an inline TVF that returns sales data for a specific product.

CREATE FUNCTION GetSalesByProduct (@ProductID INT)
RETURNS TABLE
AS
RETURN
(
SELECT SaleID, SaleDate, Amount
FROM Sales
WHERE ProductID = @ProductID
);

SELECT *
FROM GetSalesByProduct(101);

Inline Table-Valued Functions are a powerful feature in SQL Server that allows you to encapsulate and reuse complex queries with parameterization. They are efficient, easy to use, and promote cleaner code and better query organization. Use them when you need to return a set of rows based on input parameters, and prefer them over multi-statement TVFs when possible to take advantage of their performance benefits.



GitHub: https://github.com/Querymastery
Instagram: https://www.instagram.com/querymastery/
linkedin: https://www.linkedin.com/in/querymastery-m...
Facebook: https://www.facebook.com/profile.php?id=61...

Source Code: https://github.com/Querymastery/MS_SQL/blo...