Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Pendekatan paling sederhana untuk melakukan operasi penyalinan massal SQL Server adalah dengan melakukan satu operasi terhadap database. Secara default, operasi penyalinan massal dilakukan sebagai operasi yang terisolasi: operasi penyalinan terjadi dengan cara tanpa transaksi, tanpa peluang untuk memutarnya kembali.
Catatan
Jika Anda perlu mengembalikan semua atau sebagian dari salinan massal saat terjadi kesalahan, Anda dapat menggunakan transaksi yang dikelola oleh SqlBulkCopy, atau melakukan operasi penyalinan massal dalam transaksi yang ada.
SqlBulkCopy juga akan bekerja dengan System.Transactions jika koneksi terdaftar (secara implisit atau eksplisit) ke dalam transaksi System.Transactions .
Untuk informasi selengkapnya, lihat Operasi Transaksi dan Penyalinan Massal.
Langkah-langkah umum untuk melakukan operasi penyalinan massal adalah sebagai berikut:
Hubungkan ke server sumber dan dapatkan data yang akan disalin. Data juga dapat berasal dari sumber lain, jika dapat diambil dari objek IDataReader atau DataTable.
Sambungkan ke server tujuan (kecuali Anda ingin
SqlBulkCopymembuat koneksi untuk Anda).Buat objek SqlBulkCopy, mengatur semua properti yang diperlukan.
Atur properti
DestinationTableNameuntuk menetapkan tabel target untuk operasi penyisipan data besar-besaran.Panggil salah satu metode
WriteToServer.Secara opsional, perbarui properti dan panggil
WriteToServerlagi seperlunya.Panggil Close, atau bungkus operasi penyalinan massal dalam pernyataan
Using.
Perhatian
Kami merekomendasikan agar tipe data kolom sumber dan kolom target sesuai. Jika jenis data tidak cocok, SqlBulkCopy upaya untuk mengonversi setiap nilai sumber ke jenis data target, menggunakan aturan yang digunakan oleh Value. Konversi dapat memengaruhi kinerja, dan juga dapat mengakibatkan kesalahan yang tidak terduga. Misalnya, tipe data Double dapat dikonversi ke tipe data Decimal hampir sepanjang waktu, tetapi tidak selalu.
Contoh
Aplikasi konsol berikut menunjukkan cara memuat data menggunakan kelas SqlBulkCopy. Dalam contoh ini, SqlDataReader digunakan untuk menyalin data dari tabel Production.Product di database SQL Server AdventureWorks ke tabel serupa dalam database yang sama.
Penting
Sampel ini tidak akan berjalan kecuali Anda telah membuat tabel kerja seperti yang dijelaskan dalam Penyiapan Contoh Salinan Massal. Kode ini disediakan untuk menunjukkan sintaksis hanya untuk menggunakan SqlBulkCopy . Jika tabel sumber dan tujuan terletak di instans SQL Server yang sama, akan lebih mudah dan lebih cepat untuk menggunakan pernyataan INSERT … SELECT Transact-SQL untuk menyalin data.
static void Main()
{
var connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
long countStart = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine($"Starting row count = {countStart}");
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
commandSourceData.ExecuteReader();
// Open the destination connection. In the real world you would
// not use SqlBulkCopy to move data from one table to the other
// in the same database. This is for demonstration purposes only.
using (SqlConnection destinationConnection =
new(connectionString))
{
destinationConnection.Open();
// Set up the bulk copy object.
// Note that the column positions in the source
// data reader match the column positions in
// the destination table so there is no need to
// map columns.
using (SqlBulkCopy bulkCopy =
new(destinationConnection))
{
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 = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine($"Ending row count = {countEnd}");
Console.WriteLine($"{countEnd - countStart} rows were added.");
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
}
}
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 New SqlCommand( _
"SELECT ProductID, Name, ProductNumber " & _
"FROM Production.Product;", sourceConnection)
Dim reader As SqlDataReader = commandSourceData.ExecuteReader
' Open the destination connection. In the real world you would
' not use SqlBulkCopy to move data from one table to the other
' in the same database. This is for demonstration purposes only.
Using destinationConnection As SqlConnection = _
New SqlConnection(connectionString)
destinationConnection.Open()
' Set up the bulk copy object.
' The column positions in the source data reader
' match the column positions in the destination table,
' so there is no need to map columns.
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(destinationConnection)
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 Using
End Sub
Private Function GetConnectionString() As String
Throw New NotImplementedException()
End Function
End Module
Melakukan Operasi Salin Massal Menggunakan Transact-SQL dan Kelas Perintah
Contoh berikut mengilustrasikan cara menggunakan metode ExecuteNonQuery untuk melaksanakan pernyataan BULK INSERT.
Catatan
Jalur file sumber data bergantung pada server. Proses server harus memiliki akses ke jalur itu agar operasi penyalinan massal berhasil.
Using connection As SqlConnection = New SqlConnection(connectionString)
Dim queryString As String = _
"BULK INSERT Northwind.dbo.[Order Details] FROM " & _
"'f:\mydata\data.tbl' WITH (FORMATFILE='f:\mydata\data.fmt' )"
connection.Open()
SqlCommand command = New SqlCommand(queryString, connection);
command.ExecuteNonQuery()
End Using
using (SqlConnection connection = New SqlConnection(connectionString))
{
string queryString = "BULK INSERT Northwind.dbo.[Order Details] " +
"FROM 'f:\mydata\data.tbl' " +
"WITH ( FORMATFILE='f:\mydata\data.fmt' )";
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
}