Friday, December 19, 2008

Table-Valued Parameters (TVP) in SQL Server 2008

Support of Table-Valued Parameters is another great new feature in SQL Server 2008.

I am sure that all of us had to make a stored procedure or function call in SQL Server many times. In the cases where many values should be passed as parameters it was a little bit difficult as we had to use some really long lines of code. Not any more with Table-Valued Parameters :)

The usual procedure for using TVPs is the following:

1. Create a user-defined table type that can be passed as a TVP to a function or stored procedure

Code Example:
--Create a table type
(ID int,
NAME varchar(50))

2. Create a stored procedure or function that uses a TVP

Code Example:
--Create a stored procedure that takes as a parameter a TVP
CREATE PROCEDURE showTVPValues(@TVParameter employee READONLY)

SELECT * FROM @TVParameter

3. Declare the table type variable

Code Example:
--Declare a variable that references the user-defined table type
DECLARE @TVP_Param AS employee;

4. Populate the table type variable with data

Code Example:
--Add data to the table variable
FROM [table_name].[column_name];

5. Pass the table type variable as a parameter to the stored procedure

Code Example:
--Pass the table variable to the stored procedure
EXEC showTVPValues @TVP_Param;

With this way you can pass tabular data to a function or stored procedure as a single parameter.
Check out my latest eBook on SQL Server:
Tuning SQL Server - Ebook

Easily secure your SQL Server instances! Try out DBA Security Advisor!
DBA Security Advisor for SQL Server by SQLArtBits
DBA Security Advisor was developed by SQLArtBits. The tool was being carefully developed for an entire year and it contains comprehensive security checks and recommendations based on proven SQL Server security best practices. Feel free to download and use the Community Edition which is free and if you find it useful, you can consider upgrading to the Enterprise Edition!

Artemakis Artemiou [MVP]

Author & Editor

Artemakis Artemiou is a Senior SQL Server Architect, Software Developer and Microsoft Data Platform MVP. He is also an author, regular blogger, president of Cyprus.NET User Group and CY Country leader of INETA-EU. He is also the creator of DBA Security Advisor and In-Memory OLTP Simulator. Artemakis is a frequent guest author of worldwide well-respected online journals where he writes articles focusing on many SQL Server topics.

Reference: The SQL Server and .NET Hub (