[英]Passing IEnumerable<string> to a SQL Server stored procedure as a user defined table type parameter
I am attempting to pass a list of strings as a parameter into a store procedure that is expecting a UDT of a table with a single column. 我试图将字符串列表作为参数传递到存储过程中,该存储过程期望具有单列的表的UDT。 I am running into errors with SqlCommand object, and I've found posts that say to use a DataTable: 我在使用SqlCommand对象时遇到错误,并且发现一些帖子说要使用DataTable:
How to pass User Defined Table Type as Stored Procedured parameter in C# 如何在C#中将用户定义的表类型作为存储过程参数传递
I am wondering if there is an easier way considering that I don't have multiple columns. 我想知道是否考虑到没有多列的情况,是否有一种更简单的方法。 In the procedure, I am working with the table type as a sub-select against other tables, so it would be nice to keep this functionality. 在此过程中,我正在使用表类型作为对其他表的子选择,因此最好保留此功能。
Is there a better way, or just convert to DataTable? 有没有更好的方法,还是只是转换为DataTable?
Thanks! 谢谢!
You don't have to use DataTable
: 您不必使用DataTable
:
System.Data.SqlClient supports populating table-valued parameters from
DataTable
,DbDataReader
orSystem.Collections.Generic.IEnumerable<SqlDataRecord>
([T:System.Collections.Generic.IEnumerable`1)] objects. System.Data.SqlClient支持从DataTable
,DbDataReader
或System.Collections.Generic.IEnumerable<SqlDataRecord>
([T:System.Collections.Generic.IEnumerable`1)]对象中填充表值参数。 You must specify a type name for the table-valued parameter by using the TypeName property of a SqlParameter. 您必须使用SqlParameter的TypeName属性为表值参数指定类型名称。 The TypeName must match the name of a compatible type previously created on the server. TypeName必须与先前在服务器上创建的兼容类型的名称匹配。 The following code fragment demonstrates how to configure SqlParameter to insert data. 下面的代码片段演示了如何配置SqlParameter插入数据。
The above is from Table-Valued Parameters (MSDN) . 以上是来自表值参数(MSDN)的 。
... but using DataTable
is probably much easier than the alternatives; ...但是使用DataTable
可能比其他方法容易得多; here's a simple example showing how to create a DataTable
from an IEnumerable<string>
: 这是一个简单的示例,显示了如何从IEnumerable<string>
创建DataTable
:
IEnumerable<string> strings = new List<string>() { "blah", "blah blah", "blah blah blah" };
DataTable table = new DataTable();
table.Columns.Add(
new DataColumn()
{
DataType = Type.GetType("System.String"),
ColumnName = "String"
});
DataRow row;
foreach (string aString in strings)
{
row = table.NewRow();
row["String"] = aString;
table.Rows.Add(row);
}
Kenny's advice was what I was looking for. 肯尼的建议就是我想要的。 Here's the actual implementation, minus the normal command initialization. 这是实际的实现,减去常规的命令初始化。
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn()
{ DataType = Type.GetType("System.String"), ColumnName = "colname" });
DataRow row;
stringArray.ToList().ForEach(s =>
{
row = dt.NewRow();
row["colname"] = s;
dt.Rows.Add(row);
});
cmd.Parameters.Add(new SqlParameter("@colname", SqlDbType.Structured)
{
Direction = ParameterDirection.Input,
Value = dt,
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.