c# – 将DataTable作为参数发送到存储过程
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 将DataTable作为参数发送到存储过程,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2722字,纯文字阅读大概需要4分钟。
内容图文
我正在尝试使用c#,.net 2.0和SQLServer 2012 Express将DataTable发送到存储过程.
这大致就是我正在做的事情:
//define the DataTable
var accountIdTable = new DataTable("[dbo].[TypeAccountIdTable]");
//define the column
var dataColumn = new DataColumn {ColumnName = "[ID]", DataType = typeof (Guid)};
//add column to dataTable
accountIdTable.Columns.Add(dataColumn);
//feed it with the unique contact ids
foreach (var uniqueId in uniqueIds)
{
accountIdTable.Rows.Add(uniqueId);
}
using (var sqlCmd = new SqlCommand())
{
//define command details
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "[dbo].[msp_Get_Many_Profiles]";
sqlCmd.Connection = dbConn; //an open database connection
//define parameter
var sqlParam = new SqlParameter();
sqlParam.ParameterName = "@tvp_account_id_list";
sqlParam.SqlDbType = SqlDbType.Structured;
sqlParam.Value = accountIdTable;
//add parameter to command
sqlCmd.Parameters.Add(sqlParam);
//execute procedure
rResult = sqlCmd.ExecuteReader();
//print results
while (rResult.Read())
{
PrintRowData(rResult);
}
}
但后来我收到以下错误:
ArgumentOutOfRangeException: No mapping exists from SqlDbType Structured to a known DbType.
Parameter name: SqlDbType
在进一步调查(在MSDN,SO和其他地方)时,似乎.net 2.0不支持向数据库发送DataTable(缺少诸如SqlParameter.TypeName之类的东西),但我仍然不确定,因为我没有看到有人明确声称此功能在.net 2.0中不可用
这是真的?
如果是这样,是否有另一种方法将数据集合发送到数据库?
提前致谢!
解决方法:
开箱即用,ADO.NET没有充分理由支持这一点. DataTable可以占用任意数量的列,这些列可能会也可能不会映射到数据库中的实际表.
如果我理解你想要做什么 – 快速将DataTable的内容上传到具有相同结构的预定义真实表,我建议你调查SQLBulkCopy.
从文档:
Microsoft SQL Server includes a popular command-prompt utility named
bcp for moving data from one table to another, whether on a single
server or between servers. The SqlBulkCopy class lets you write
managed code solutions that provide similar functionality. There are
other ways to load data into a SQL Server table (INSERT statements,
for example), but SqlBulkCopy offers a significant performance
advantage over them.The SqlBulkCopy class can be used to write data only to SQL Server
tables. However, the data source is not limited to SQL Server; any
data source can be used, as long as the data can be loaded to a
DataTable instance or read with a IDataReader instance.SqlBulkCopy will fail when bulk loading a DataTable column of type
SqlDateTime into a SQL Server column whose type is one of the
date/time types added in SQL Server 2008.
但是,您可以在更高版本的SQL Server中定义表值参数,并使用它在您要求的方法中发送表(DateTable).在http://sqlwithmanoj.wordpress.com/2012/09/10/passing-multipledynamic-values-to-stored-procedures-functions-part4-by-using-tvp/有一个例子
内容总结
以上是互联网集市为您收集整理的c# – 将DataTable作为参数发送到存储过程全部内容,希望文章能够帮你解决c# – 将DataTable作为参数发送到存储过程所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。