SqlBulkCopyColumnMappingCollection.Add 메서드

정의

오버로드

Add(SqlBulkCopyColumnMapping)

지정된 매핑을 SqlBulkCopyColumnMappingCollection에 추가합니다.

Add(Int32, Int32)

소스 및 대상 열을 모두 지정하는 서수를 사용하여 새 SqlBulkCopyColumnMapping을 만들어 컬렉션에 추가합니다.

Add(Int32, String)

소스 열에 대한 서수와 대상 열에 대한 문자열을 사용하여 새 SqlBulkCopyColumnMapping을 만들어 컬렉션에 추가합니다.

Add(String, Int32)

소스 열을 설명하는 열 이름과 대상 열을 지정하는 서수를 사용하여 새 SqlBulkCopyColumnMapping을 만들어 컬렉션에 추가합니다.

Add(String, String)

소스 및 대상 열을 모두 지정하는 열 이름을 사용하여 새 SqlBulkCopyColumnMapping을 만들어 컬렉션에 추가합니다.

Add(SqlBulkCopyColumnMapping)

지정된 매핑을 SqlBulkCopyColumnMappingCollection에 추가합니다.

public:
 System::Data::SqlClient::SqlBulkCopyColumnMapping ^ Add(System::Data::SqlClient::SqlBulkCopyColumnMapping ^ bulkCopyColumnMapping);
public System.Data.SqlClient.SqlBulkCopyColumnMapping Add (System.Data.SqlClient.SqlBulkCopyColumnMapping bulkCopyColumnMapping);
member this.Add : System.Data.SqlClient.SqlBulkCopyColumnMapping -> System.Data.SqlClient.SqlBulkCopyColumnMapping
Public Function Add (bulkCopyColumnMapping As SqlBulkCopyColumnMapping) As SqlBulkCopyColumnMapping

매개 변수

bulkCopyColumnMapping
SqlBulkCopyColumnMapping

컬렉션에 추가될 매핑을 설명하는 SqlBulkCopyColumnMapping 개체입니다.

반환

SqlBulkCopyColumnMapping

SqlBulkCopyColumnMapping 개체입니다.

예제

다음 예제에서는 AdventureWorks 샘플 데이터베이스의 원본 테이블에서 동일한 데이터베이스의 대상 테이블로 데이터를 대량 복사합니다. 대상의 열 수가 원본의 열 수와 일치하지만 열 이름과 서수 위치는 일치하지 않습니다. SqlBulkCopyColumnMapping 개체는 대량 복사에 대한 열 맵을 만드는 데 사용됩니다.

중요

대량 복사 예제 설정에 설명된 대로 작업 테이블을 만들지 않으면 이 샘플이 실행되지 않습니다. 이 코드는 SqlBulkCopy 를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server 인스턴스에 있는 경우 Transact-SQL INSERT ... SELECT 문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.

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.BulkCopyDemoDifferentColumns;",
                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();

            // Set up the bulk copy object.
            using (SqlBulkCopy bulkCopy =
                       new SqlBulkCopy(connectionString))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoDifferentColumns";

                // Set up the column mappings by name.
                SqlBulkCopyColumnMapping mapID =
                    new SqlBulkCopyColumnMapping("ProductID", "ProdID");
                bulkCopy.ColumnMappings.Add(mapID);

                SqlBulkCopyColumnMapping mapName =
                    new SqlBulkCopyColumnMapping("Name", "ProdName");
                bulkCopy.ColumnMappings.Add(mapName);

                SqlBulkCopyColumnMapping mapMumber =
                    new SqlBulkCopyColumnMapping("ProductNumber", "ProdNum");
                bulkCopy.ColumnMappings.Add(mapMumber);

                // Write from the source to the destination.
                try
                {
                    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.BulkCopyDemoDifferentColumns;", _
                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

            ' Set up the bulk copy object.
            Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(connectionString)
                bulkCopy.DestinationTableName = _
                "dbo.BulkCopyDemoDifferentColumns"

                ' Set up the column mappings by name.
                Dim mapID As New _
                  SqlBulkCopyColumnMapping("ProductID", "ProdID")
                bulkCopy.ColumnMappings.Add(mapID)

                Dim mapName As New _
                 SqlBulkCopyColumnMapping("Name", "ProdName")
                bulkCopy.ColumnMappings.Add(mapName)

                Dim mapMumber As New _
                 SqlBulkCopyColumnMapping("ProductNumber", "ProdNum")
                bulkCopy.ColumnMappings.Add(mapMumber)

                ' Write from the source to the destination.
                Try
                    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

추가 정보

적용 대상

Add(Int32, Int32)

소스 및 대상 열을 모두 지정하는 서수를 사용하여 새 SqlBulkCopyColumnMapping을 만들어 컬렉션에 추가합니다.

public:
 System::Data::SqlClient::SqlBulkCopyColumnMapping ^ Add(int sourceColumnIndex, int destinationColumnIndex);
public System.Data.SqlClient.SqlBulkCopyColumnMapping Add (int sourceColumnIndex, int destinationColumnIndex);
member this.Add : int * int -> System.Data.SqlClient.SqlBulkCopyColumnMapping
Public Function Add (sourceColumnIndex As Integer, destinationColumnIndex As Integer) As SqlBulkCopyColumnMapping

매개 변수

sourceColumnIndex
Int32

데이터 소스 내에 있는 소스 열의 위치입니다.

destinationColumnIndex
Int32

대상 테이블 내에 있는 대상 열의 위치입니다.

반환

SqlBulkCopyColumnMapping

열 매핑입니다.

예제

다음 예제에서는 AdventureWorks 샘플 데이터베이스의 원본 테이블에서 동일한 데이터베이스의 대상 테이블로 데이터를 대량 복사합니다. 대상의 열 수가 원본의 열 수와 일치하지만 열 이름과 서수 위치는 일치하지 않습니다. SqlBulkCopyColumnMapping 개체는 원본 및 대상 열의 서수 위치를 사용하여 대량 복사에 대한 열 맵을 만드는 데 사용됩니다.

중요

대량 복사 예제 설정에 설명된 대로 작업 테이블을 만들지 않으면 이 샘플이 실행되지 않습니다. 이 코드는 SqlBulkCopy 를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server 인스턴스에 있는 경우 Transact-SQL INSERT ... SELECT 문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.

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.BulkCopyDemoDifferentColumns;",
                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();

            // Set up the bulk copy object.
            using (SqlBulkCopy bulkCopy =
                       new SqlBulkCopy(connectionString))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoDifferentColumns";

                // The column order in the source doesn't match the order
                // in the destination, so ColumnMappings must be defined.
                bulkCopy.ColumnMappings.Add(0, 0);
                bulkCopy.ColumnMappings.Add(1, 2);
                bulkCopy.ColumnMappings.Add(2, 1);

                // Write from the source to the destination.
                try
                {
                    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.BulkCopyDemoDifferentColumns;", _
                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

            ' Set up the bulk copy object.
            Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(connectionString)
                bulkCopy.DestinationTableName = _
                "dbo.BulkCopyDemoDifferentColumns"

                ' The column order in the source doesn't match the order 
                ' in the destination, so ColumnMappings must be defined.
                bulkCopy.ColumnMappings.Add(0, 0)
                bulkCopy.ColumnMappings.Add(1, 2)
                bulkCopy.ColumnMappings.Add(2, 1)

                ' Write from the source to the destination.
                Try
                    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

설명

컬렉션의 매핑은 모든 정수/정수 쌍, 모든 문자열/문자열 쌍, 모든 정수/문자열 쌍 또는 모든 문자열/정수 쌍 중 하나여야 합니다. 컬렉션에 이미 있는 다른 매핑과 다른 매핑을 추가하려고 하면 throw InvalidOperationException 됩니다.

추가 정보

적용 대상

Add(Int32, String)

소스 열에 대한 서수와 대상 열에 대한 문자열을 사용하여 새 SqlBulkCopyColumnMapping을 만들어 컬렉션에 추가합니다.

public:
 System::Data::SqlClient::SqlBulkCopyColumnMapping ^ Add(int sourceColumnIndex, System::String ^ destinationColumn);
public System.Data.SqlClient.SqlBulkCopyColumnMapping Add (int sourceColumnIndex, string destinationColumn);
member this.Add : int * string -> System.Data.SqlClient.SqlBulkCopyColumnMapping
Public Function Add (sourceColumnIndex As Integer, destinationColumn As String) As SqlBulkCopyColumnMapping

매개 변수

sourceColumnIndex
Int32

데이터 소스 내에 있는 소스 열의 위치입니다.

destinationColumn
String

대상 테이블 내에 있는 대상 열의 이름입니다.

반환

SqlBulkCopyColumnMapping

열 매핑입니다.

예제

다음 예제에서는 AdventureWorks 샘플 데이터베이스의 원본 테이블에서 동일한 데이터베이스의 대상 테이블로 데이터를 대량 복사합니다. 대상의 열 수가 원본의 열 수와 일치하지만 열 이름과 서수 위치는 일치하지 않습니다. SqlBulkCopyColumnMapping 개체는 대량 복사에 대한 열 맵을 만드는 데 사용됩니다.

중요

대량 복사 예제 설정에 설명된 대로 작업 테이블을 만들지 않으면 이 샘플이 실행되지 않습니다. 이 코드는 SqlBulkCopy 를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server 인스턴스에 있는 경우 Transact-SQL INSERT ... SELECT 문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.

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.BulkCopyDemoDifferentColumns;",
                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();

            // Set up the bulk copy object.
            using (SqlBulkCopy bulkCopy =
                       new SqlBulkCopy(connectionString))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoDifferentColumns";

                // The column order in the source doesn't match the order
                // in the destination, so ColumnMappings must be defined.
                bulkCopy.ColumnMappings.Add(0, "ProdID");
                bulkCopy.ColumnMappings.Add(1, "ProdName");
                bulkCopy.ColumnMappings.Add(2, "ProdNum");

                // Write from the source to the destination.
                try
                {
                    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.BulkCopyDemoDifferentColumns;", _
                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

            ' Set up the bulk copy object.
            Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(connectionString)
                bulkCopy.DestinationTableName = _
                "dbo.BulkCopyDemoDifferentColumns"

                ' The column order in the source doesn't match the order 
                ' in the destination, so ColumnMappings must be defined.
                bulkCopy.ColumnMappings.Add(0, "ProdID")
                bulkCopy.ColumnMappings.Add(1, "ProdName")
                bulkCopy.ColumnMappings.Add(2, "ProdNum")

                ' Write from the source to the destination.
                Try
                    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

설명

컬렉션의 매핑은 모든 정수/정수 쌍, 모든 문자열/문자열 쌍, 모든 정수/문자열 쌍 또는 모든 문자열/정수 쌍 중 하나여야 합니다. 컬렉션에 이미 있는 다른 매핑과 다른 매핑을 추가하려고 하면 throw InvalidOperationException 됩니다.

추가 정보

적용 대상

Add(String, Int32)

소스 열을 설명하는 열 이름과 대상 열을 지정하는 서수를 사용하여 새 SqlBulkCopyColumnMapping을 만들어 컬렉션에 추가합니다.

public:
 System::Data::SqlClient::SqlBulkCopyColumnMapping ^ Add(System::String ^ sourceColumn, int destinationColumnIndex);
public System.Data.SqlClient.SqlBulkCopyColumnMapping Add (string sourceColumn, int destinationColumnIndex);
member this.Add : string * int -> System.Data.SqlClient.SqlBulkCopyColumnMapping
Public Function Add (sourceColumn As String, destinationColumnIndex As Integer) As SqlBulkCopyColumnMapping

매개 변수

sourceColumn
String

데이터 소스 내에 있는 소스 열의 이름입니다.

destinationColumnIndex
Int32

대상 테이블 내에 있는 대상 열의 위치입니다.

반환

SqlBulkCopyColumnMapping

열 매핑입니다.

예제

다음 예제에서는 AdventureWorks 샘플 데이터베이스의 원본 테이블에서 동일한 데이터베이스의 대상 테이블로 데이터를 대량 복사합니다. 대상의 열 수가 원본의 열 수와 일치하지만 열 이름과 서수 위치는 일치하지 않습니다. SqlBulkCopyColumnMapping 개체는 대량 복사에 대한 열 맵을 만드는 데 사용됩니다.

중요

대량 복사 예제 설정에 설명된 대로 작업 테이블을 만들지 않으면 이 샘플이 실행되지 않습니다. 이 코드는 SqlBulkCopy 를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server 인스턴스에 있는 경우 Transact-SQL INSERT ... SELECT 문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.

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.BulkCopyDemoDifferentColumns;",
                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();

            // Set up the bulk copy object.
            using (SqlBulkCopy bulkCopy =
                       new SqlBulkCopy(connectionString))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoDifferentColumns";

                // The column order in the source doesn't match the order
                // in the destination, so ColumnMappings must be defined.
                bulkCopy.ColumnMappings.Add("ProductID", 0);
                bulkCopy.ColumnMappings.Add("ProductNumber", 1);
                bulkCopy.ColumnMappings.Add("Name", 2);

                // Write from the source to the destination.
                try
                {
                    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.BulkCopyDemoDifferentColumns;", _
                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

            ' Set up the bulk copy object.
            Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(connectionString)
                bulkCopy.DestinationTableName = _
                "dbo.BulkCopyDemoDifferentColumns"

                ' The column order in the source doesn't match the order 
                ' in the destination, so ColumnMappings must be defined.
                bulkCopy.ColumnMappings.Add("ProductID", 0)
                bulkCopy.ColumnMappings.Add("ProductNumber", 1)
                bulkCopy.ColumnMappings.Add("Name", 2)

                ' Write from the source to the destination.
                Try
                    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

설명

컬렉션의 매핑은 모든 정수/정수 쌍, 모든 문자열/문자열 쌍, 모든 정수/문자열 쌍 또는 모든 문자열/정수 쌍 중 하나여야 합니다. 컬렉션에 이미 있는 다른 매핑과 다른 매핑을 추가하려고 하면 throw InvalidOperationException 됩니다.

추가 정보

적용 대상

Add(String, String)

소스 및 대상 열을 모두 지정하는 열 이름을 사용하여 새 SqlBulkCopyColumnMapping을 만들어 컬렉션에 추가합니다.

public:
 System::Data::SqlClient::SqlBulkCopyColumnMapping ^ Add(System::String ^ sourceColumn, System::String ^ destinationColumn);
public System.Data.SqlClient.SqlBulkCopyColumnMapping Add (string sourceColumn, string destinationColumn);
member this.Add : string * string -> System.Data.SqlClient.SqlBulkCopyColumnMapping
Public Function Add (sourceColumn As String, destinationColumn As String) As SqlBulkCopyColumnMapping

매개 변수

sourceColumn
String

데이터 소스 내에 있는 소스 열의 이름입니다.

destinationColumn
String

대상 테이블 내에 있는 대상 열의 이름입니다.

반환

SqlBulkCopyColumnMapping

열 매핑입니다.

예제

다음 예제에서는 AdventureWorks 샘플 데이터베이스의 원본 테이블에서 동일한 데이터베이스의 대상 테이블로 데이터를 대량 복사합니다. 대상의 열 수가 원본의 열 수와 일치하지만 열 이름과 서수 위치는 일치하지 않습니다. 이 코드는 열 이름을 지정하여 개체를 만듭니다 SqlBulkCopyColumnMapping .

중요

대량 복사 예제 설정에 설명된 대로 작업 테이블을 만들지 않으면 이 샘플이 실행되지 않습니다. 이 코드는 SqlBulkCopy 를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server 인스턴스에 있는 경우 Transact-SQL INSERT ... SELECT 문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.

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.BulkCopyDemoDifferentColumns;",
                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();

            // Set up the bulk copy object.
            using (SqlBulkCopy bulkCopy =
                       new SqlBulkCopy(connectionString))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoDifferentColumns";

                // The column order in the source doesn't match the order
                // in the destination, so ColumnMappings must be defined.
                bulkCopy.ColumnMappings.Add("ProductID", "ProdID");
                bulkCopy.ColumnMappings.Add("Name", "ProdName");
                bulkCopy.ColumnMappings.Add("ProductNumber", "ProdNum");

                // Write from the source to the destination.
                try
                {
                    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.BulkCopyDemoDifferentColumns;", _
                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

            ' Set up the bulk copy object.
            Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(connectionString)
                bulkCopy.DestinationTableName = _
                "dbo.BulkCopyDemoDifferentColumns"

                ' The column order in the source doesn't match the order 
                ' in the destination, so ColumnMappings must be defined.
                bulkCopy.ColumnMappings.Add("ProductID", "ProdID")
                bulkCopy.ColumnMappings.Add("Name", "ProdName")
                bulkCopy.ColumnMappings.Add("ProductNumber", "ProdNum")

                ' Write from the source to the destination.
                Try
                    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

설명

컬렉션의 매핑은 모든 정수/정수 쌍, 모든 문자열/문자열 쌍, 모든 정수/문자열 쌍 또는 모든 문자열/정수 쌍 중 하나여야 합니다. 컬렉션에 이미 있는 다른 매핑과 다른 매핑을 추가하려고 하면 throw InvalidOperationException 됩니다.

추가 정보

적용 대상