이제 이런저런 이유로 코드도 필요하고 그렇군요 흠... 벌크 insert할때 사용할 수 있는 방법입니다만... 문제는...
Datatable 을 만들어줘야 하는 것이고... 기존 Data를 Update하는 부분은 없군요... 삭제라도 할 수 있어야 하는데...
SqlBulkCopy 클래스
데이터가 있는 SQL Server 테이블을 다른 소스에서 대량으로 로드하는 작업을 효율적으로 수행할 수 있습니다.
네임스페이스: System.Data.SqlClient
어셈블리: System.Data(System.Data.dll)
SqlBulkCopy 형식에서는 다음과 같은 멤버를 노출합니다.
이름 설명
SqlBulkCopy(SqlConnection)
지정된 SqlConnection의 열려 있는 인스턴스를 사용하여 SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다.
SqlBulkCopy(String)
제공된 connectionString을 기반으로 하는 SqlConnection의 새 인스턴스를 초기화하고 엽니다. 이 생성자는 SqlConnection을 사용하여SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다.
SqlBulkCopy(String, SqlBulkCopyOptions)
제공된 connectionString을 기반으로 하는 SqlConnection의 새 인스턴스를 초기화하고 엽니다. 이 생성자는 SqlConnection을 사용하여SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다. SqlConnection 인스턴스는 copyOptions 매개 변수에 제공된 옵션에 따라 작동합니다.
SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)
제공된 SqlConnection의 이미 열려 있는 인스턴스를 사용하여 SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다. SqlBulkCopy 인스턴스는 copyOptions 매개 변수에 제공된 옵션에 따라 작동합니다. 제공된 SqlTransaction이 null이 아니면 복사 작업이 해당 트랜잭션 내에서 수행됩니다.
위쪽
이름 설명
BatchSize
각 일괄 작업에 포함된 행의 수입니다. 각 일괄 작업이 끝나면 해당 일괄 작업에 포함된 행이 서버로 전송됩니다.
BulkCopyTimeout
제한 시간에 도달하기 전까지 작업을 완료해야 하는 시간(초)입니다.
ColumnMappings
SqlBulkCopyColumnMapping 항목의 컬렉션을 반환합니다. 열 매핑은 데이터 소스 열과 대상 열 사이의 관계를 정의합니다.
DestinationTableName
서버에 있는 대상 테이블의 이름입니다.
NotifyAfter
알림 이벤트를 생성하기 전에 처리할 행의 수를 정의합니다.
위쪽
이름 설명
Close
SqlBulkCopy 인스턴스를 닫습니다.
Equals(Object)
지정한 Object가 현재 Object와 같은지 여부를 확인합니다. (Object에서 상속됨)
Finalize
가비지 수집에서 회수하기 전에 개체에서 리소스를 해제하고 다른 정리 작업을 수행할 수 있게 합니다. (Object에서 상속됨)
GetHashCode
특정 형식에 대한 해시 함수 역할을 합니다. (Object에서 상속됨)
GetType
현재 인스턴스의 Type을 가져옵니다. (Object에서 상속됨)
MemberwiseClone
현재 Object의 단순 복사본을 만듭니다. (Object에서 상속됨)
ToString
현재 개체를 나타내는 문자열을 반환합니다. (Object에서 상속됨)
WriteToServer(DataRow())
제공된 DataRow 배열의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사합니다.
WriteToServer(DataTable)
제공된 DataTable의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사합니다.
WriteToServer(IDataReader)
제공된 IDataReader의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사합니다.
WriteToServer(DataTable, DataRowState)
제공된 DataTable에서 제공된 행 상태와 일치하는 행만을 SqlBulkCopy 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사합니다.
위쪽
Microsoft SQL Server에는 단일 서버에서 또는 여러 서버 간에 테이블의 데이터를 다른 테이블로 이동할 때 많이 사용하는 bcp라는 명령 프롬프트 유틸리티가 포함되어 있습니다.SqlBulkCopy 클래스를 사용하면 비슷한 기능을 제공하는 관리되는 코드 솔루션을 작성할 수 있습니다. 또한 INSERT 문 등을 사용하여 SQL Server 테이블로 데이터를 로드하는 방법도 있지만 SqlBulkCopy를 사용하면 다른 방법에 비해 성능이 향상됩니다.
SqlBulkCopy 클래스는 SQL Server 테이블에 데이터를 쓸 때에만 사용됩니다. 그러나 데이터를 DataTable 인스턴스에 로드하거나 IDataReader 인스턴스로 데이터를 읽을 수 있는 경우 SQL Server를 포함한 모든 데이터 소스를 사용할 수 있습니다.
SqlDateTime 형식의 DataTable 열을 SQL Server 2008에 추가된 날짜/시간 형식 중 하나의 형식을 가진 SQL Server 열에 대량 로드할 경우 SqlBulkCopy가 실패합니다.
다음 콘솔 응용 프로그램에서는 SqlBulkCopy 클래스를 사용하여 데이터를 로드하는 방법을 보여 줍니다. 이 예제에서는 SqlDataReader를 사용하여 SQL Server 2005 AdventureWorks 데이터베이스에 있는 Production.Product 테이블의 데이터를 같은 데이터베이스의 비슷한 테이블로 복사합니다.
대량 복사 예제 설정(ADO.NET)에서 설명하는 대로 작업 테이블을 만들지 않으면 이 샘플이 실행되지 않습니다. 이 코드는 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.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();
}
}
}
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;";
}
}
Windows 7, Windows Vista SP1 이상, Windows XP SP3, Windows XP SP2 x64 버전, Windows Server 2008(Server Core는 지원되지 않음), Windows Server 2008 R2(Server Core는 SP1 이상에서 지원됨), Windows Server 2003 SP2
.NET Framework에서 모든 플랫폼의 전체 버전을 지원하지는 않습니다. 지원되는 버전의 목록을 보려면 .NET Framework 시스템 요구 사항을 참조하십시오.
SQL Server에서의 대량 복사 작업(ADO.NET)
데이터가 있는 SQL Server 테이블을 다른 소스에서 대량으로 로드하는 작업을 효율적으로 수행할 수 있습니다.
어셈블리: System.Data(System.Data.dll)
SqlBulkCopy 형식에서는 다음과 같은 멤버를 노출합니다.
이름 | 설명 | |
---|---|---|
SqlBulkCopy(SqlConnection) | 지정된 SqlConnection의 열려 있는 인스턴스를 사용하여 SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다. | |
SqlBulkCopy(String) | 제공된 connectionString을 기반으로 하는 SqlConnection의 새 인스턴스를 초기화하고 엽니다. 이 생성자는 SqlConnection을 사용하여SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다. | |
SqlBulkCopy(String, SqlBulkCopyOptions) | 제공된 connectionString을 기반으로 하는 SqlConnection의 새 인스턴스를 초기화하고 엽니다. 이 생성자는 SqlConnection을 사용하여SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다. SqlConnection 인스턴스는 copyOptions 매개 변수에 제공된 옵션에 따라 작동합니다. | |
SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) | 제공된 SqlConnection의 이미 열려 있는 인스턴스를 사용하여 SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다. SqlBulkCopy 인스턴스는 copyOptions 매개 변수에 제공된 옵션에 따라 작동합니다. 제공된 SqlTransaction이 null이 아니면 복사 작업이 해당 트랜잭션 내에서 수행됩니다. |
이름 | 설명 | |
---|---|---|
BatchSize | 각 일괄 작업에 포함된 행의 수입니다. 각 일괄 작업이 끝나면 해당 일괄 작업에 포함된 행이 서버로 전송됩니다. | |
BulkCopyTimeout | 제한 시간에 도달하기 전까지 작업을 완료해야 하는 시간(초)입니다. | |
ColumnMappings | SqlBulkCopyColumnMapping 항목의 컬렉션을 반환합니다. 열 매핑은 데이터 소스 열과 대상 열 사이의 관계를 정의합니다. | |
DestinationTableName | 서버에 있는 대상 테이블의 이름입니다. | |
NotifyAfter | 알림 이벤트를 생성하기 전에 처리할 행의 수를 정의합니다. |
이름 | 설명 | |
---|---|---|
Close | SqlBulkCopy 인스턴스를 닫습니다. | |
Equals(Object) | 지정한 Object가 현재 Object와 같은지 여부를 확인합니다. (Object에서 상속됨) | |
Finalize | 가비지 수집에서 회수하기 전에 개체에서 리소스를 해제하고 다른 정리 작업을 수행할 수 있게 합니다. (Object에서 상속됨) | |
GetHashCode | 특정 형식에 대한 해시 함수 역할을 합니다. (Object에서 상속됨) | |
GetType | 현재 인스턴스의 Type을 가져옵니다. (Object에서 상속됨) | |
MemberwiseClone | 현재 Object의 단순 복사본을 만듭니다. (Object에서 상속됨) | |
ToString | 현재 개체를 나타내는 문자열을 반환합니다. (Object에서 상속됨) | |
WriteToServer(DataRow()) | 제공된 DataRow 배열의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사합니다. | |
WriteToServer(DataTable) | 제공된 DataTable의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사합니다. | |
WriteToServer(IDataReader) | 제공된 IDataReader의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사합니다. | |
WriteToServer(DataTable, DataRowState) | 제공된 DataTable에서 제공된 행 상태와 일치하는 행만을 SqlBulkCopy 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사합니다. |
Microsoft SQL Server에는 단일 서버에서 또는 여러 서버 간에 테이블의 데이터를 다른 테이블로 이동할 때 많이 사용하는 bcp라는 명령 프롬프트 유틸리티가 포함되어 있습니다.SqlBulkCopy 클래스를 사용하면 비슷한 기능을 제공하는 관리되는 코드 솔루션을 작성할 수 있습니다. 또한 INSERT 문 등을 사용하여 SQL Server 테이블로 데이터를 로드하는 방법도 있지만 SqlBulkCopy를 사용하면 다른 방법에 비해 성능이 향상됩니다.
SqlBulkCopy 클래스는 SQL Server 테이블에 데이터를 쓸 때에만 사용됩니다. 그러나 데이터를 DataTable 인스턴스에 로드하거나 IDataReader 인스턴스로 데이터를 읽을 수 있는 경우 SQL Server를 포함한 모든 데이터 소스를 사용할 수 있습니다.
SqlDateTime 형식의 DataTable 열을 SQL Server 2008에 추가된 날짜/시간 형식 중 하나의 형식을 가진 SQL Server 열에 대량 로드할 경우 SqlBulkCopy가 실패합니다.
다음 콘솔 응용 프로그램에서는 SqlBulkCopy 클래스를 사용하여 데이터를 로드하는 방법을 보여 줍니다. 이 예제에서는 SqlDataReader를 사용하여 SQL Server 2005 AdventureWorks 데이터베이스에 있는 Production.Product 테이블의 데이터를 같은 데이터베이스의 비슷한 테이블로 복사합니다.
대량 복사 예제 설정(ADO.NET)에서 설명하는 대로 작업 테이블을 만들지 않으면 이 샘플이 실행되지 않습니다. 이 코드는 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.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(); } } } 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;"; } }
Windows 7, Windows Vista SP1 이상, Windows XP SP3, Windows XP SP2 x64 버전, Windows Server 2008(Server Core는 지원되지 않음), Windows Server 2008 R2(Server Core는 SP1 이상에서 지원됨), Windows Server 2003 SP2
.NET Framework에서 모든 플랫폼의 전체 버전을 지원하지는 않습니다. 지원되는 버전의 목록을 보려면 .NET Framework 시스템 요구 사항을 참조하십시오.SqlBulkCopyOptions 열거형
업데이트: 2007년 11월
SqlBulkCopy의 인스턴스와 함께 사용할 하나 이상의 옵션을 지정하는 비트 플래그입니다.
이 열거형에는 멤버 값을 비트로 조합할 수 있는 FlagsAttribute 특성이 있습니다.
네임스페이스: System.Data.SqlClient
어셈블리: System.Data(System.Data.dll)
멤버 이름 | 설명 | |
---|---|---|
Default | 모든 옵션에 대해 기본값을 사용합니다. | |
KeepIdentity | 소스 ID 값을 유지합니다. 지정되지 않은 경우, 대상에서 ID 값을 할당합니다. | |
CheckConstraints | 데이터가 삽입되는 동안 제약 조건을 검사합니다. 기본적으로 제약 조건은 검사되지 않습니다. | |
TableLock | 대량 복사 작업 기간에 대한 대량 업데이트 잠금을 가져옵니다. 지정되지 않은 경우, 행 잠금이 사용됩니다. | |
KeepNulls | 기본값 설정에 관계없이 대상 테이블에 null 값을 유지합니다. 지정되지 않은 경우, 기본값이 적용되는 경우 null 값은 기본값으로 대체됩니다. | |
FireTriggers | 지정된 경우, 서버에서는 데이터베이스에 삽입되는 행에 대해 삽입 트리거를 발생시킵니다. | |
UseInternalTransaction | 지정된 경우 대량 복사 작업의 각 일괄 작업은 한 트랜잭션 내에서 발생합니다. 이 옵션을 지정하고 SqlTransaction 개체를 생성자에게 제공하면 ArgumentException이 발생합니다. |
SqlBulkCopy 인스턴스를 생성할 때 SqlBulkCopyOptions 열거형을 사용하여 해당 인스턴스에 대한 WriteToServer 메서드의 동작을 변경할 수 있습니다.
다음 콘솔 응용 프로그램에서는 각 행의 ID 열에 새 값을 생성하는 대신 대량 로드를 수행하여 소스 테이블의 ID 열에 있는 값을 대상 테이블의 해당 열로 복사하는 방법을 보여 줍니다.
옵션에 따라 대량 로드 작업이 작동하는 방식을 확인하려면 dbo.BulkCopyDemoMatchingColumns 테이블을 비운 채로 샘플을 실행합니다. 모든 행이 소스에서 로드됩니다. 그런 다음 테이블을 비우지 않은 채로 샘플을 다시 실행합니다. 그러면 예외가 throw되고, 코드는 기본 키 위반으로 인해 행이 추가되지 않았음을 알리는 메시지를 콘솔 창에 씁니다.
대량 복사 예제 설정(ADO.NET) 에서 설명하는 대로 작업 테이블을 만들지 않으면 이 샘플이 실행되지 않습니다. 이 코드는 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.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;"; } }
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98
.NET Framework 및 .NET Compact Framework에서 모든 플랫폼의 전체 버전을 지원하지는 않습니다. 지원되는 버전의 목록을 보려면 .NET Framework 시스템 요구 사항을 참조하십시오.
'Brain Trainning > PRG Language' 카테고리의 다른 글
[WEB] Status Code (책펌) (0) | 2012.01.25 |
---|---|
[C#] Bulk Insert into SQL Server (0) | 2012.01.17 |
[C#] Import Excel to GridView (0) | 2011.12.30 |
[C#] MVC Tutorials (0) | 2011.11.27 |
[GeoIP] .NET API 테스트 결과 (0) | 2011.06.13 |