如何在ado.net中将表索引复制到另一个表

本文关键字:索引 复制 另一个 ado net | 更新日期: 2023-09-27 18:21:36

我在ado.net中使用SqlBulkCopy将一个表复制到另一个表。代码为:

    using (sourceConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["OTPTestConnectionString"].ConnectionString))
    {
        sourceConnection.Open();
        // Get data from the source table as a SqlDataReader.
        SqlCommand commandSourceData = new SqlCommand("SELECT * FROM " + sourceTableName, sourceConnection);
        SqlDataReader reader = commandSourceData.ExecuteReader();
        using (destConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLExpressDatabaseConnectionString"].ConnectionString))
        {
            destConnection.Open();
            // Perform bulk copy
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destConnection))
            {
                bulkCopy.DestinationTableName = destTableName;
                // Write from the source to the destination.
                bulkCopy.WriteToServer(reader);
            }
        }
        reader.Close();
...

它工作正常,但不能将原始表中的主键索引复制到新表中。我想知道如何在Ado.net中做到这一点。谢谢。

如何在ado.net中将表索引复制到另一个表

我使用SqlBulkCopyOptions.KeepIdentity来计算。代码是

        SqlBulkCopyOptions options = SqlBulkCopyOptions.KeepIdentity;
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destConnection.ConnectionString, options))
        {
            bulkCopy.DestinationTableName = destTableName;
                // Write from the source to the destination.
            bulkCopy.WriteToServer(reader);
        }