批量插入生成的ids返回顺序

时间:2017-02-01 15:25:03

标签: sql-server

我希望从C#应用程序高效地执行DataTable到SQLServer的批量插入,并以正确的顺序检索插入的ID。 为了使插入的主键自动递增值,我在同一连接上使用以下方法:

  1. 创建表#StagingTable(....)“
  2. 将DataTable批量插入#S​​tagingTable
  3. 执行读者:

    insert into DestinationTable(....<columns_list>...)
    output inserted.ID -- primary key which is auto increment
    select <columns_list> from #StagingTable
    
  4. 然后在C#中我读取列表中的所有生成的ID。读取顺序未正确映射到DataTable.Rows顺序。

  5. 我的问题是:     如果我在不做任何映射的情况下对这个id列表进行排序(即c#simple:list.Sort()) - 这是正确的插入顺序,以便table.Rows[k]对应id = list[k]吗?

    谢谢!

    /编辑:

    为了给你完整的上下文,我在C#

    中有这样的方法
    using System.Data;
    using System.Data.SqlClient;
    using System.Web.UI.WebControls;
    
    public static class SQLWrite
    {
        public static void BulkWrite(this DataTable table, string destinationTable, SqlConnection connection, int batchSize)
        {
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
            string columnNamesAndSQLType = string.Join(", ", Enumerable.Range(0, table.Columns.Count).
                Where(i => !table.Columns[i].AutoIncrement).
                Select(i => "[" + table.Columns[i].ColumnName + "] " +
                    Parameter.ConvertTypeCodeToDbType(Type.GetTypeCode(table.Columns[i].DataType)).ToString()));
            string columnNames = string.Join(", ", Enumerable.Range(0, table.Columns.Count).
                Where(i => !table.Columns[i].AutoIncrement).
                Select(i => "[" + table.Columns[i].ColumnName + "]"));
            using (var command = connection.CreateCommand())
            {
                command.CommandText = @"
    CREATE  TABLE #StagingTable(
        RowNumber INT IDENTITY(1, 1) NOT NULL, 
        " + columnNamesAndSQLType + @")     ";
                command.ExecuteNonQuery();
            }
            DataColumn autoIncrementColumn = null;
            using (var copy = new SqlBulkCopy(connection))
            {
                copy.BatchSize = batchSize;
                copy.DestinationTableName = destinationTable;
                foreach (DataColumn column in table.Columns)
                {
                    if (column.AutoIncrement)
                    {
                        autoIncrementColumn = column;
                        continue;
                    }
                    copy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
                }
                copy.WriteToServer(table);
            }
            using (var command = connection.CreateCommand())
            {
                command.CommandText = @"
    INSERT  INTO dbo.DestinationTable(" + columnNames + @")
    OUTPUT  INSERTED.ID 
    SELECT  " + columnNames + @"
    FROM    #StagingTable 
    ORDER   BY RowNumber    
    ";   //Will the inserted ID values be retrieved in the natural order of insertion - by RowNumber ?
                using (var reader = command.ExecuteReader())
                {
                    List<long> list = new List<long>();
                    while (reader.Read())
                    {
                        list.Add(reader.GetInt64(0));
                    }
                    list.Sort();
                    int rowIndex = 0;
                    foreach (DataRow row in table.Rows)
                    {
                        row[autoIncrementColumn] = list[rowIndex];
                        rowIndex++;
                    }
                }
            }
            if (connection.State != ConnectionState.Closed)
            {
                connection.Close();
            }
        }
    }
    

    假设每个表都有一个名为ID的bigint主键自动增量列。 我想知道上面的代码是否检索SQL生成的IDS并将它们与数据表正确关联。

0 个答案:

没有答案