将数据表传递给存储过程
我有一个用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 )
-
您需要定义要在数据库中的用户定义表类型中传递的表类型 。
-
然后,您需要在存储过程中添加参数以将其传递给:
@YourCustomTable AS [dbo].YourCustomTable Readonly,
-
然后,当您设置行时,请按以下方式调用它:
// 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参数传递给数据库。
上述就是C#学习教程:将数据表传递给存储过程分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。
如若转载,请注明出处:https://www.ctvol.com/cdevelopment/953159.html