In this article I will explain with an example, how to pass Table as parameter i.e. Table Valued Parameters to Stored Procedure in SQL Server.
The User Defined Table Type has to be created in SQL Server and it must have the same schema as that of the Table Valued parameter that we need to pass to the Stored Procedure.
I have made use of the following table Customers with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
Creating User Defined Table Type
A User Defined Table Type needs to be created in SQL Server using the following query.
CREATE TYPE [dbo].[CustomerType] AS TABLE(
[Id] [int] NULL,
[Name] [varchar](100) NULL,
[Country] [varchar](50) NULL
Once the User Defined Table Type is created it will be visible in the Object Explorer as shown below.
Creating Stored Procedure to Pass Table as Parameter (Table Valued Parameters)
The following Stored Procedure needs to be created which will accept the Table of CustomerType Type as parameter.
CREATE PROCEDURE [dbo].[Insert_Customers]
@tblCustomers CustomerType READONLY
SET NOCOUNT ON;
INSERT INTO Customers(CustomerId, Name, Country)
SELECT Id, Name, Country FROM @tblCustomers
Executing Stored Procedure
A table variable of type CustomerType is created and then some records are inserted into it.
Then the table variable is passed as parameter to the Stored Procedure and the Stored Procedure is executed which finally inserts the records into the Customers Table.
DECLARE @tblCustomers CustomerType
INSERT INTO @tblCustomers
SELECT 1, 'John Hammond', 'United States'
SELECT 2, 'Mudassar Khan', 'India'
SELECT 3, 'Suzanne Mathews', 'France'
SELECT 4, 'Robert Schidner', 'Russia'
EXEC [dbo].[Insert_Customers] @tblCustomers