SQL Server User-Defined Table Types for Efficient Data Insertion

🚀 **How to Use User-Defined Table Types in SQL Server** One powerful feature in SQL Server is the **User-Defined Table Type**. It allows you to create a reusable table structure and pass multiple rows of data into stored procedures in a single call. This is cleaner and faster than sending rows one by one. 📌 Best suited for **small to medium-sized batches of data**. 🔹 **1. Create a Table Type** CREATE TYPE EmployeeTableType AS TABLE (   Id INT,   Name VARCHAR(100),   Salary DECIMAL(10,2) ); This creates a reusable table definition inside your database. --- 🔹 **2. Use It in a Stored Procedure** CREATE PROCEDURE InsertEmployees   @Employees EmployeeTableType READONLY AS BEGIN   INSERT INTO Employees (Id, Name, Salary)   SELECT Id, Name, Salary   FROM @Employees; END 📌 Table-valued parameters must always be `READONLY`. --- 🔹 **3. Execute the Procedure** DECLARE @Emp EmployeeTableType; INSERT INTO @Emp VALUES (1, 'John', 5000), (2, 'Sara', 6000), (3, 'Ali', 7000); EXEC InsertEmployees @Emp; --- 💡 **Why Use It?** Instead of calling a procedure multiple times: EXEC InsertEmployee 1,'John',5000 EXEC InsertEmployee 2,'Sara',6000 EXEC InsertEmployee 3,'Ali',7000 You send all rows in one request. ✅ Better performance ✅ Cleaner code ✅ Less network traffic ✅ Easier maintenance --- 📌 **Common Use Cases** • Bulk inserts from applications • Passing list of IDs • Importing Excel data • Batch updates • Reusable structured parameters --- ⚡ If you need to pass multiple rows into SQL Server efficiently, User-Defined Table Types are a feature worth knowing. #SQLServer #Database #TSQL #DotNet #BackendDevelopment #SoftwareEngineering #Programming #Performance

To view or add a comment, sign in

Explore content categories