c# - 插入列表到没有存储过程的临时表
问题描述
我有一个整数列表List<int> lstIds
。现在我想将所有这些添加ID
到一个临时表中。
我知道一些不同的方法,比如使用SqlCommand
需要进行多个数据库调用的参数,这是不可取的。另外,我不想使用存储过程。
那么,是否可以将整个List
插入临时表中?如果是,那么如何?
注意:解决方案LINQ
也可以。
编辑:有人将此标记为此问题的重复项,而在给定问题中,他们将DataTable
其作为临时表,而在这里我想将数据存储在 SQL Server 临时表中。
解决方案
当您想使用 ADO.NET 将某种数组数据传递到 SQL Server 2008 或更高版本时,您可以定义和使用表值参数:
CREATE TYPE integer_list_tbltype AS TABLE (n int NULL)
然后,您可以在 C# 代码中执行以下操作:
List<int> integers = new List<int> { 1, 2, 3 };
DataTable dataTable = new DataTable();
dataTable.Columns.Add("n", typeof(int));
dataTable.SetTypeName("integer_list_tbltype");
foreach (int i in integers)
dataTable.Rows.Add(i);
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO YourTable (n) SELECT n FROM @integers";
cmd.Parameters.Add("@integers", SqlDbType.Structured);
cmd.Parameters["@integers"].Direction = ParameterDirection.Input;
cmd.Parameters["@integers"].TypeName = "integer_list_tbltype";
cmd.Parameters["@integers"].Value = dataTable;
cmd.ExecuteNonQuery();
}
更多信息请参考 Erland Sommarskog 的文章:http: //www.sommarskog.se/arrays-in-sql-2008.html
推荐阅读
- java - Cassandra 和 thrift 协议中的“显示版本”
- c# - 转换器定义的 WPF MediaElement 源抛出 NullException
- php - 奇怪的问题:PHP 今年返回错误的复活节日期
- ghost-blog - 如何在 .env 文件中为 Ghost 指定数组?
- javascript - 子组件的 EventEmitter “失去”父组件的观察者
- ruby-on-rails - 具有参数、锚点和类的相同页面 link_to 语法
- microsoft-graph-api - 使用 MS Graph Explorer 将自适应卡片发送到通道 - 我可以删除顶部的填充吗?
- batch-file - 删除除 123、1234 和 12345 以外的所有文件夹
- azure - azurerm_function_app 瞬态错误 - “不支持操作:不支持 RepoUrl VSTSRM”
- c# - 访问被拒绝。(HRESULT 异常:0x80070005 (E_ACCESSDENIED))为某些用户重置密码时