使用c#进行大容量复制时,标识列插入不工作

本文关键字:标识 插入 工作 大容量 复制 使用 | 更新日期: 2023-09-27 18:07:03

我在Prod中有一个SOURCE表:

    SELECT '-1' as PKey, NULL as ID, 'Unknown' as Name
    UNION
    SELECT '1' as PKey, 01 as ID, 'ABC' as Name
    UNION
    SELECT '2' as PKey, 02 as ID, 'XYZ' as Name

我想复制(移动)到DEV环境。为此,我有一个Foreach循环容器,包含以下三个任务:

1) Identity_Insert ON:检查表是否有任何标识列,如果是,然后将其设置为ON(我已经测试过了,它有效)

2) Script_task_1:它使用以下代码将数据从PROD移动到DEV

    try{
        string connectionString =
                @"Data Source=Prod_Server;Initial Catalog=Source_DB;Integrated Security=SSPI;";
        // get the source data
        using (SqlConnection sourceConnection =
                new SqlConnection(connectionString))
        {
            SqlCommand myCommand =
                new SqlCommand("SELECT * FROM " + TableName, sourceConnection);
            sourceConnection.Open();
            SqlDataReader reader = myCommand.ExecuteReader();
            // open the destination data
            string connectionString1 = @"Data Source=Dev_Server;Initial Catalog=Dest_DB;Integrated Security=SSPI;";
            using (SqlConnection destinationConnection =
                        new SqlConnection(connectionString1))
            {
                // open the connection
                destinationConnection.Open();
                using (SqlBulkCopy bulkCopy =
                new SqlBulkCopy(destinationConnection.ConnectionString, SqlBulkCopyOptions.KeepNulls & SqlBulkCopyOptions.KeepIdentity))
                {
                    bulkCopy.BatchSize = 500;
                    bulkCopy.NotifyAfter = 1000;
                    bulkCopy.SqlRowsCopied +=
                        new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
                    bulkCopy.DestinationTableName = TableName;
                    bulkCopy.WriteToServer(reader);
                }
            }
            reader.Close();
            //MessageBox.Show("Data copied successfully!!");
        }
        }
            catch(Exception E){
                Console.WriteLine(E.Message);
            }

3) Identity_Insert OFF:检查表是否有标识列,如果有,则设置为OFF

在这个过程之后,我的目标表看起来像这样:

    SELECT '1' as PKey, NULL as ID, 'Unknown' as Name
    UNION
    SELECT '2' as PKey, 01 as ID, 'ABC' as Name
    UNION
    SELECT '3' as PKey, 02 as ID, 'XYZ' as Name

因此,它正确地复制了数据,但是根记录的Identity字段没有复制。从1开始,而不是-1。

有人知道我在这里做错了什么吗?

使用c#进行大容量复制时,标识列插入不工作

我相信你想看看批量插入图书在线文档的KeepIdentity部分。