Passing A Table To A Stored Procedure In SQL Server Using Table Valued Parameters

Many times we come across a situation where we need to pass a table to stored procedure from C# code. In such scenarios what we can do is either loop through table and send rows one by one or we can directly pass the full table to the procedure. Passing rows one by one may be inefficient as we have to iterate through rows and call procedure again and again.

SQL Server provides us an efficient way of doing the same using 'User Defined Types' So for passing a table valued parameter to a stored procedure we need to create a user defined table type that will have same columns that we want to pass to the table. Click Database Node > Programmability > Types, then User-Defined Table Types. Now we create a table which will be filled by stored procedure.
  1. CREATE TABLE [dbo].[Employee](  
  2.  [Emp_ID] [int] IDENTITY(1,1) NOT NULL,  
  3.  [Emp_name] [varchar](100) NULL,  
  4.  [Emp_Sal] [decimal](10, 2) NULL  
  5. ON [PRIMARY]  
  6.   
  7. GO  
Once the table is being created we need to create a type same as that of a table.
  1. CREATE TYPE Employee AS TABLE   
  2. (  
  3.  [Emp_ID] [int] IDENTITY(1,1) NOT NULL,  
  4.  [Emp_name] [varchar](100) NULL,  
  5.  [Emp_Sal] [decimal](10, 2) NULL  
  6. )  
  7. GO  
Now we are done with creating a type and a table we need to create a stored procedure that will accept a type and insert into the table using the type.
  1. CREATE PROCEDURE sp_InsertEmployee  
  2.  @employees employee READONLY  
  3.    
  4.   AS  
  5.  INSERT INTO Employee(Emp_name,Emp_Sal)  
  6.    
  7.  SELECT Emp_name,Emp_Sal  
  8.  FROM @employees   
Where @employees is a table valued parameter passed to the stored procedure. Now we are done with creating a procedure, its time to check how it works. You can pass a datatable from C# or VB code as a parameter. What I will do here as a demonstration I will create a table variable and pass that table to the stored procedure.
  1. DECLARE @testtable employee  
  2.   INSERT INTO @testtable(Emp_name,Emp_Sal)  
  3.  VALUES ('Anees', 1000.00),  
  4. ('Rick', 1200.00),  
  5. ('John', 1100.00)  
  6. select * from @testtable  
Now we have our table ready. We need to pass it to stored procedure and see the result.
  1. DECLARE @testtable employee  
  2.   INSERT INTO @testtable(Emp_name,Emp_Sal)  
  3.  VALUES ('Anees', 1000.00),  
  4. ('Rick', 1200.00),  
  5. ('John', 1100.00)  
  6.   
  7. exec  sp_InsertEmployee @testtable  
  8. select * from Employee  


Similar Articles