Pass table valued parameter using ADO.NET Pass table valued parameter using ADO.NET asp.net asp.net

Pass table valued parameter using ADO.NET


  1. Create type in SQL Server:

    CREATE TYPE [dbo].[MyDataType] As Table(    ID INT,    Name NVARCHAR(50))
  2. Create Procedure:

    CREATE PROCEDURE [dbo].[MyProcedure](    @myData As [dbo].[MyDataType] Readonly)ASBEGIN    SELECT * FROM @myDataEND
  3. Create DataTable in C#:

    DataTable myDataTable = new DataTable("MyDataType");myDataTable.Columns.Add("Name", typeof(string));myDataTable.Columns.Add("Id", typeof(Int32));myDataTable.Rows.Add("XYZ", 1);myDataTable.Rows.Add("ABC", 2);
  4. Create SQL Parameter:

    SqlParameter parameter = new SqlParameter();parameter.ParameterName = "@myData";parameter.SqlDbType = System.Data.SqlDbType.Structured;parameter.Value = myDataTable;command.Parameters.Add(parameter); 


I tried this and received the exception:

The table type parameter '@MyDataType' must have a valid type name.

I had to set the "TypeName" property of the SqlParameter:

parameter.TypeName = "MyDataType";


This question is a duplicate of How to pass table value parameters to stored procedure from .net code. Please see that question for an example illustrating the use of either a DataTable or an IEnumerable<SqlDataRecord>.