Using Table-Valued Parameters for Bulk Operations
By Tom Nonmacher
In the world of SQL Server, efficient data handling is a necessity. One of the most effective ways to handle bulk data operations is through the use of Table-Valued Parameters (TVPs). Available in SQL Server 2016 and later, TVPs allow you to send multiple rows of data to a function or stored procedure without creating a temporary table or multiple parameters. This is a powerful tool for executing complex batch operations, boosting performance, and simplifying your SQL code.
To define a TVP, we first need to create a table type. This definition will specify the structure of the table that we will use as a parameter in our stored procedure or function. Here's an example using T-SQL:
-- Creating a table type
CREATE TYPE dbo.OrderTableType AS TABLE
(
OrderID INT,
OrderDate DATE,
CustomerID INT
);
After defining our table type, we can use it as a parameter in a stored procedure. The stored procedure will use this table as input and perform operations, such as inserts, updates, or deletes on the main database table. Here's a stored procedure example that inserts data from the TVP into an Orders table:
-- Creating a stored procedure
CREATE PROCEDURE InsertOrders @OrderTable OrderTableType READONLY
AS
BEGIN
INSERT INTO Orders (OrderID, OrderDate, CustomerID)
SELECT OrderID, OrderDate, CustomerID FROM @OrderTable
END;
Unfortunately, MySQL 5.7 and Azure SQL do not natively support TVPs. But you can achieve similar results by creating a temporary table, performing your operations, and then dropping the table. It's more cumbersome but it works. For DB2 11.1, you can use the ARRAY data type to pass an array of values to a stored procedure, which is slightly similar to a TVP but not as flexible.
In conclusion, TVPs are a powerful tool in SQL Server 2016 and later for performing bulk operations efficiently and cleanly. They reduce the amount of code needed, improve performance by reducing network round trips, and increase the readability of your SQL code. If you're working with bulk operations in SQL Server, consider employing TVPs in your toolbox.