将数据表传递给存储过程

我有一个用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 } 

我有一个存储过程

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

我想要的是将数据表传递给这个存储过程,怎么样?

从SQL Server 2008 / .NET 3.5开始,您可以使用表值参数….

查看MSDN上的指南

此外,由于还有其他可用选项,我比较了将多个值(单个字段)传递给sproc的三种方法( TVP vs XML vs CSV )

  1. 您需要定义要在数据库中的用户定义表类型中传递的表类型

  2. 然后,您需要在存储过程中添加参数以将其传递给:

     @YourCustomTable AS [dbo].YourCustomTable Readonly, 
  3. 然后,当您设置行时,请按以下方式调用它:

     // 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(); 

这应该可以解决您的问题

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