gpt4 book ai didi

c# - 将 IEnumerable 作为用户定义的表类型参数传递给 SQL Server 存储过程

转载 作者:太空宇宙 更新时间:2023-11-03 20:05:35 25 4
gpt4 key购买 nike

我正在尝试将字符串列表作为参数传递到存储过程中,该存储过程需要具有单列的表的 UDT。我在使用 SqlCommand 对象时遇到错误,我发现帖子说要使用 DataTable:

How to pass User Defined Table Type as Stored Procedured parameter in C#

考虑到我没有多列,我想知道是否有更简单的方法。在此过程中,我将表类型作为针对其他表的子选择,因此最好保留此功能。

有没有更好的办法,还是直接转成DataTable?

谢谢!

最佳答案

您不必使用 DataTable :

System.Data.SqlClient supports populating table-valued parameters from DataTable, DbDataReader or System.Collections.Generic.IEnumerable<SqlDataRecord> ([T:System.Collections.Generic.IEnumerable`1)] objects. You must specify a type name for the table-valued parameter by using the TypeName property of a SqlParameter. The TypeName must match the name of a compatible type previously created on the server. The following code fragment demonstrates how to configure SqlParameter to insert data.

以上来自Table-Valued Parameters (MSDN) .

... 但使用 DataTable可能比其他选择容易得多;这是一个简单的例子,展示了如何创建 DataTable来自 IEnumerable<string> :

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);
}

关于c# - 将 IEnumerable<string> 作为用户定义的表类型参数传递给 SQL Server 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23688158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com