In this article I will explain with an example, how to pass Table Variable as Parameter to Stored Procedure in SQL Server.
A Table Variable of User Defined Table Type has to be created of the same schema as that of the Table Valued parameter and then it is passed as Parameter to the Stored Procedure in SQL Server.
Database
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
)
GO
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 Variable as Parameter
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
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Customers(CustomerId, Name, Country)
SELECT Id, Name, Country FROM @tblCustomers
END
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'
UNION ALL
SELECT 2, 'Mudassar Khan', 'India'
UNION ALL
SELECT 3, 'Suzanne Mathews', 'France'
UNION ALL
SELECT 4, 'Robert Schidner', 'Russia'
EXEC [dbo].[Insert_Customers] @tblCustomers
Screenshot