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.
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 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
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.
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