c# – 将DataTable作为参数发送到存储过程
我正在尝试使用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. 从文档:
但是,您可以在更高版本的SQL Server中定义表值参数,并使用它在您要求的方法中发送表(DateTable).在http://sqlwithmanoj.wordpress.com/2012/09/10/passing-multipledynamic-values-to-stored-procedures-functions-part4-by-using-tvp/有一个例子 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |