简体   繁体   中英

Passing datatable to a stored procedure

I have a datatable created in C#.

using (DataTable dt = new DataTable())
{
    dt.Columns.Add("MetricId", typeof(int));
    dt.Columns.Add("Descr", typeof(string));
    dt.Columns.Add("EntryDE", typeof(int));
    foreach (DataGridViewRow row in dgv.Rows)
    {
        dt.Rows.Add(row.Cells[1].Value, row.Cells[2].Value, row.Cells[0].Value);
    }

    // TODO: pass dt
}

And I have a stored procedure

CREATE PROCEDURE [dbo].[Admin_Fill] 
-- Add the parameters for the stored procedure here
@MetricId INT,
@Descr VARCHAR(100),
@EntryDE VARCHAR(20)

What I want is to pass the datatable to this stored procedure, how?

You can use a Table Valued Parameter as of SQL Server 2008 / .NET 3.5....

Check out the guide on MSDN

Also, as there other options available, I have a comparisonof 3 approaches of passing multiple values (single field) to a sproc ( TVP vs XML vs CSV )

  1. You need to define a Table Type that you want to pass in User-Defined Table Types in your database.

  2. Then you need to add the parameter in your Stored Procedure to pass it in like this:

     @YourCustomTable AS [dbo].YourCustomTable Readonly, 
  3. Then, when you have your rows setup, call it like this:

     // Setup SP and Parameters command.CommandText = "YOUR STORED PROC NAME"; command.Parameters.Clear(); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@someIdForParameter", someId); command.Parameters.AddWithValue("@YourCustomTable",dtCustomerFields).SqlDbType = SqlDbType.Structured; //Execute command.ExecuteNonQuery(); 

This should resolve your problem

我们通常将数据喷射到XML文档中,并将数据作为NTEXT参数传递给数据库。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM