首页 > 解决方案 > 插入列表到没有存储过程的临时表

问题描述

我有一个整数列表List<int> lstIds。现在我想将所有这些添加ID到一个临时表中。

我知道一些不同的方法,比如使用SqlCommand需要进行多个数据库调用的参数,这是不可取的。另外,我不想使用存储过程。

那么,是否可以将整个List插入临时表中?如果是,那么如何?

注意:解决方案LINQ也可以。

编辑:有人将此标记为此问题的重复项,而在给定问题中,他们将DataTable其作为临时表,而在这里我想将数据存储在 SQL Server 临时表中。

标签: c#sql-serverlinqcollectionslinq-to-sql

解决方案


当您想使用 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


推荐阅读