SqlBulkCopyOptions Enum

Definisi

Bendera bitwise yang menentukan satu atau beberapa opsi untuk digunakan dengan instans SqlBulkCopy.

Enumerasi ini mendukung kombinasi bitwise dari nilai yang termasuk di dalamnya.

public enum class SqlBulkCopyOptions
[System.Flags]
public enum SqlBulkCopyOptions
[<System.Flags>]
type SqlBulkCopyOptions = 
Public Enum SqlBulkCopyOptions
Warisan
SqlBulkCopyOptions
Atribut

Bidang

AllowEncryptedValueModifications 64

Ketika ditentukan, AllowEncryptedValueModifications memungkinkan penyalinan massal data terenkripsi antara tabel atau database, tanpa mendekripsi data. Biasanya, aplikasi akan memilih data dari kolom terenkripsi dari satu tabel tanpa mendekripsi data (aplikasi akan terhubung ke database dengan kata kunci pengaturan enkripsi kolom diatur ke dinonaktifkan) dan kemudian akan menggunakan opsi ini untuk menyisipkan data secara massal, yang masih dienkripsi. Untuk informasi selengkapnya, lihat Always Encrypted.

Berhati-hatilah saat menentukan AllowEncryptedValueModifications karena ini dapat menyebabkan kerusakan database karena driver tidak memeriksa apakah data memang dienkripsi, atau apakah data dienkripsi dengan benar menggunakan jenis enkripsi, algoritma, dan kunci yang sama dengan kolom target.

CheckConstraints 2

Periksa batasan saat data sedang disisipkan. Secara default, batasan tidak diperiksa.

Default 0

Gunakan nilai default untuk semua opsi.

FireTriggers 16

Ketika ditentukan, menyebabkan server mengaktifkan pemicu penyisipan untuk baris yang dimasukkan ke dalam database.

KeepIdentity 1

Mempertahankan nilai identitas sumber. Ketika tidak ditentukan, nilai identitas ditetapkan oleh tujuan.

KeepNulls 8

Pertahankan nilai null dalam tabel tujuan terlepas dari pengaturan untuk nilai default. Ketika tidak ditentukan, nilai null digantikan oleh nilai default jika berlaku.

TableLock 4

Dapatkan kunci pembaruan massal selama durasi operasi penyalinan massal. Ketika tidak ditentukan, kunci baris digunakan.

UseInternalTransaction 32

Ketika ditentukan, setiap batch operasi penyalinan massal akan terjadi dalam transaksi. Jika Anda menunjukkan opsi ini dan juga memberikan SqlTransaction objek ke konstruktor, terjadi ArgumentException .

Contoh

Aplikasi konsol berikut menunjukkan cara melakukan pemuatan massal yang menyalin nilai di kolom identitas tabel sumber ke kolom terkait dalam tabel tujuan, alih-alih menghasilkan nilai baru untuk setiap kolom identitas baris.

Untuk melihat bagaimana opsi mengubah cara kerja beban massal, jalankan sampel dengan dbo. Tabel BulkCopyDemoMatchingColumns kosong. Semua baris dimuat dari sumber. Selanjutnya, jalankan sampel lagi tanpa mengosongkan tabel. Pengecualian dilemparkan, dan kode menulis pesan ke jendela konsol yang memberi tahu Anda bahwa baris tidak ditambahkan karena pelanggaran kunci primer.

Penting

Sampel ini tidak akan berjalan kecuali Anda telah membuat tabel kerja seperti yang dijelaskan dalam Penyiapan Contoh Salinan Massal. Kode ini disediakan untuk mendemonstrasikan sintaks untuk menggunakan SqlBulkCopy saja. Jika tabel sumber dan tujuan berada dalam instans SQL Server yang sama, lebih mudah dan lebih cepat untuk menggunakan pernyataan Transact-SQL INSERT … SELECT untuk menyalin data.

using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        // Open a sourceConnection to the AdventureWorks database.
        using (SqlConnection sourceConnection =
                   new SqlConnection(connectionString))
        {
            sourceConnection.Open();

            // Perform an initial count on the destination table.
            SqlCommand commandRowCount = new SqlCommand(
                "SELECT COUNT(*) FROM " +
                "dbo.BulkCopyDemoMatchingColumns;",
                sourceConnection);
            long countStart = System.Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Starting row count = {0}", countStart);

            // Get data from the source table as a SqlDataReader.
            SqlCommand commandSourceData = new SqlCommand(
                "SELECT ProductID, Name, " +
                "ProductNumber " +
                "FROM Production.Product;", sourceConnection);
            SqlDataReader reader =
                commandSourceData.ExecuteReader();

            // Create the SqlBulkCopy object using a connection string
            // and the KeepIdentity option.
            // In the real world you would not use SqlBulkCopy to move
            // data from one table to the other in the same database.
            using (SqlBulkCopy bulkCopy =
                new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoMatchingColumns";

                try
                {
                    // Write from the source to the destination.
                    bulkCopy.WriteToServer(reader);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    // Close the SqlDataReader. The SqlBulkCopy
                    // object is automatically closed at the end
                    // of the using block.
                    reader.Close();
                }
            }

            // Perform a final count on the destination
            // table to see how many rows were added.
            long countEnd = System.Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Ending row count = {0}", countEnd);
            Console.WriteLine("{0} rows were added.", countEnd - countStart);
            Console.WriteLine("Press Enter to finish.");
            Console.ReadLine();
        }
    }

    private static string GetConnectionString()
        // To avoid storing the sourceConnection string in your code,
        // you can retrieve it from a configuration file.
    {
        return "Data Source=(local); " +
            " Integrated Security=true;" +
            "Initial Catalog=AdventureWorks;";
    }
}
Imports System.Data.SqlClient

Module Module1
    Sub Main()
        Dim connectionString As String = GetConnectionString()

        ' Open a connection to the AdventureWorks database.
        Using sourceConnection As SqlConnection = _
           New SqlConnection(connectionString)
            sourceConnection.Open()

            ' Perform an initial count on the destination table.
            Dim commandRowCount As New SqlCommand( _
            "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
                sourceConnection)
            Dim countStart As Long = _
               System.Convert.ToInt32(commandRowCount.ExecuteScalar())
            Console.WriteLine("Starting row count = {0}", countStart)

            ' Get data from the source table as a SqlDataReader.
            Dim commandSourceData As SqlCommand = New SqlCommand( _
               "SELECT ProductID, Name, ProductNumber " & _
               "FROM Production.Product;", sourceConnection)
            Dim reader As SqlDataReader = commandSourceData.ExecuteReader

            ' Create the SqlBulkCopy object using a connection string 
            ' and the KeepIdentity option. 
            ' In the real world you would not use SqlBulkCopy to move
            ' data from one table to the other in the same database.
            Using bulkCopy As SqlBulkCopy = _
              New SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity)
                bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"

                Try
                    ' Write from the source to the destination.
                    bulkCopy.WriteToServer(reader)

                Catch ex As Exception
                    Console.WriteLine(ex.Message)

                    Finally
                        ' Close the SqlDataReader. The SqlBulkCopy
                        ' object is automatically closed at the end
                        ' of the Using block.
                        reader.Close()
                End Try
            End Using

            ' Perform a final count on the destination table
            ' to see how many rows were added.
            Dim countEnd As Long = _
                System.Convert.ToInt32(commandRowCount.ExecuteScalar())
            Console.WriteLine("Ending row count = {0}", countEnd)
            Console.WriteLine("{0} rows were added.", countEnd - countStart)

            Console.WriteLine("Press Enter to finish.")
            Console.ReadLine()
        End Using
    End Sub

    Private Function GetConnectionString() As String
        ' To avoid storing the sourceConnection string in your code, 
        ' you can retrieve it from a configuration file. 
        Return "Data Source=(local);" & _
            "Integrated Security=true;" & _
            "Initial Catalog=AdventureWorks;"
    End Function
End Module

Keterangan

Anda dapat menggunakan SqlBulkCopyOptions enumerasi saat membuat SqlBulkCopy instans untuk mengubah bagaimana metode untuk instans tersebut WriteToServer berperilaku.

Berlaku untuk

Lihat juga