DestinationTableName의 이름은 세 부분으로 구성됩니다(예: <database>.<owningschema>.<name>).선택한 데이터베이스와 소유하는 스키마로 테이블 이름을 정규화할 수 있습니다.그러나 테이블 이름에 밑줄("_")이나 다른 특수 문자를 사용할 경우에는 ([<database>.<owningschema>.<name_01>])과 같이 괄호를 사용하여 이름을 이스케이프해야 합니다.자세한 내용은 SQL Server 온라인 설명서에서 "식별자"를 참조하십시오.
DestinationTableName 속성의 값(예: tempdb..#table 또는 tempdb.<owner>.#table)을 사용하여 데이터를 임시 테이블로 대량 복사할 수 있습니다.
데이터 소스와 대상 테이블의 열 수가 같고 데이터 소스 내에서 각 소스 열의 위치가 해당하는 대상 열의 위치와 일치하면 ColumnMappings 컬렉션이 필요하지 않습니다.하지만 열 수가 다르거나 위치가 일치하지 않는 경우에는ColumnMappings를 사용해야만 데이터를 올바른 열로 복사할 수 있습니다.
using System.Data.SqlClient;
class Program
{
staticvoid 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();
// 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 SqlConnection(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 SqlBulkCopy(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 = 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();
}
}
}
privatestaticstring 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;";
}