Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass table valued parameter using ADO.NET

How to pass table valued parameter to stored procedure using ADO.NET?

like image 382
NIck Avatar asked May 02 '12 07:05

NIck


People also ask

How do you use table valued parameters?

Table-valued parameters are declared by using user-defined table types. You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.

Can we pass table as a parameter to stored procedure?

Table-Valued Parameters aka TVPs are commonly used to pass a table as a parameter into stored procedures or functions. They are helpful in a way, we can use a table as an input to these routines and we can get rid of dealing more complex steps to achieve this process.

How do you pass a table as a parameter in SQL?

Create a user-defined table type that corresponds to the table that you want to populate. Pass the user-defined table to the stored procedure as a parameter. Inside the stored procedure, select the data from the passed parameter and insert it into the table that you want to populate.


1 Answers

  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 ) AS  BEGIN     SELECT * FROM @myData END 
  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);  
like image 199
Naresh Goradara Avatar answered Sep 30 '22 18:09

Naresh Goradara