From 065f6a7fb3fc80c126d99629a10eb36007468dec Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 29 Aug 2024 17:41:50 -0500 Subject: [PATCH 1/4] Batch #2 --- doc/samples/SqlBatch_ExecuteReader.cs | 46 - doc/samples/SqlBulkCopy_BatchSize.cs | 79 - doc/samples/SqlBulkCopy_ColumnMapping.cs | 92 - .../SqlBulkCopy_ColumnMappingColNameIndex.cs | 85 - .../SqlBulkCopy_ColumnMappingCollection.cs | 85 - ...BulkCopy_ColumnMappingCollectionOrdinal.cs | 85 - ...BulkCopy_ColumnMappingDestinationColumn.cs | 95 - ...ulkCopy_ColumnMappingDestinationOrdinal.cs | 95 - .../SqlBulkCopy_ColumnMappingIndexColName.cs | 85 - .../SqlBulkCopy_ColumnMappingNameOrdinal.cs | 92 - .../SqlBulkCopy_ColumnMappingOrdersDetails.cs | 168 - .../SqlBulkCopy_ColumnMappingOrdinal.cs | 92 - .../SqlBulkCopy_ColumnMappingOrdinalName.cs | 92 - .../SqlBulkCopy_ColumnMappingRemove.cs | 168 - .../SqlBulkCopy_ColumnMappingRemoveAt.cs | 171 - doc/samples/SqlBulkCopy_ColumnOrderHint.cs | 84 - .../SqlBulkCopy_ColumnOrderHintCollection.cs | 83 - ...qlBulkCopy_ColumnOrderHintCollectionAdd.cs | 86 - ...lBulkCopy_ColumnOrderHintCollectionAdd2.cs | 83 - ...BulkCopy_ColumnOrderHintCollectionClear.cs | 177 - ...ulkCopy_ColumnOrderHintCollectionRemove.cs | 176 - ...kCopy_ColumnOrderHintCollectionRemoveAt.cs | 176 - .../SqlBulkCopy_ColumnOrderHintColumn.cs | 85 - .../SqlBulkCopy_ColumnOrderHintSortOrder.cs | 85 - doc/samples/SqlBulkCopy_ConnectionString.cs | 81 - doc/samples/SqlBulkCopy_DataTable.cs | 116 - doc/samples/SqlBulkCopy_KeepIdentity.cs | 82 - doc/samples/SqlBulkCopy_NotifyAfter.cs | 91 - doc/samples/SqlBulkCopy_OrdersDetails.cs | 154 - doc/samples/SqlBulkCopy_RowArray.cs | 120 - doc/samples/SqlBulkCopy_Single.cs | 92 - .../SqlClientFactory_DataSourceEnumerator.cs | 39 - .../SqlBatchCommand.xml | 129 +- .../SqlBatchCommandCollection.xml | 88 +- .../Microsoft.Data.SqlClient/SqlBulkCopy.xml | 3534 ++++++++++------- .../SqlBulkCopyColumnMapping.xml | 1434 +++++-- .../SqlBulkCopyColumnMappingCollection.xml | 1615 ++++++-- .../SqlBulkCopyColumnOrderHint.xml | 576 ++- .../SqlBulkCopyColumnOrderHintCollection.xml | 1250 ++++-- .../SqlBulkCopyOptions.xml | 219 +- .../SqlClientDiagnostic.xml | 377 +- .../SqlClientFactory.xml | 577 ++- .../SqlClient/SqlBulkCopyColumnMapping.cs | 2 +- 43 files changed, 6931 insertions(+), 6210 deletions(-) delete mode 100644 doc/samples/SqlBatch_ExecuteReader.cs delete mode 100644 doc/samples/SqlBulkCopy_BatchSize.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMapping.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingCollection.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingRemove.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHint.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs delete mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs delete mode 100644 doc/samples/SqlBulkCopy_ConnectionString.cs delete mode 100644 doc/samples/SqlBulkCopy_DataTable.cs delete mode 100644 doc/samples/SqlBulkCopy_KeepIdentity.cs delete mode 100644 doc/samples/SqlBulkCopy_NotifyAfter.cs delete mode 100644 doc/samples/SqlBulkCopy_OrdersDetails.cs delete mode 100644 doc/samples/SqlBulkCopy_RowArray.cs delete mode 100644 doc/samples/SqlBulkCopy_Single.cs delete mode 100644 doc/samples/SqlClientFactory_DataSourceEnumerator.cs diff --git a/doc/samples/SqlBatch_ExecuteReader.cs b/doc/samples/SqlBatch_ExecuteReader.cs deleted file mode 100644 index aadfbd3508..0000000000 --- a/doc/samples/SqlBatch_ExecuteReader.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string str = "Data Source=(local);Initial Catalog=Northwind;" - + "Integrated Security=SSPI;Encrypt=False"; - RunBatch(str); - } - - static void RunBatch(string connString) - { - using var connection = new SqlConnection(connString); - connection.Open(); - - var batch = new SqlBatch(connection); - - const int count = 10; - const string parameterName = "parameter"; - for (int i = 0; i < count; i++) - { - var batchCommand = new SqlBatchCommand($"SELECT @{parameterName} as value"); - batchCommand.Parameters.Add(new SqlParameter(parameterName, i)); - batch.BatchCommands.Add(batchCommand); - } - - // Optionally Prepare - batch.Prepare(); - - var results = new List(count); - using (SqlDataReader reader = batch.ExecuteReader()) - { - do - { - while (reader.Read()) - { - results.Add(reader.GetFieldValue(0)); - } - } while (reader.NextResult()); - } - Console.WriteLine(string.Join(", ", results)); - } -} -// diff --git a/doc/samples/SqlBulkCopy_BatchSize.cs b/doc/samples/SqlBulkCopy_BatchSize.cs deleted file mode 100644 index ee0a62b53c..0000000000 --- a/doc/samples/SqlBulkCopy_BatchSize.cs +++ /dev/null @@ -1,79 +0,0 @@ -using Microsoft.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. - // 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)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - // Set the BatchSize. - bulkCopy.BatchSize = 50; - - 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;"; - } -} diff --git a/doc/samples/SqlBulkCopy_ColumnMapping.cs b/doc/samples/SqlBulkCopy_ColumnMapping.cs deleted file mode 100644 index 6908e2bbdd..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMapping.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs b/doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs deleted file mode 100644 index 9c1e797bc8..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs b/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs deleted file mode 100644 index 4cf90008c6..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs b/doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs deleted file mode 100644 index fa0db0ef4c..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs b/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs deleted file mode 100644 index d46a58a261..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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 source and destination. - SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(); - mapID.SourceColumn = "ProductID"; - mapID.DestinationColumn = "ProdID"; - bulkCopy.ColumnMappings.Add(mapID); - - SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping(); - mapName.SourceColumn = "Name"; - mapName.DestinationColumn = "ProdName"; - bulkCopy.ColumnMappings.Add(mapName); - - SqlBulkCopyColumnMapping mapNumber = new SqlBulkCopyColumnMapping(); - mapNumber.SourceColumn = "ProductNumber"; - mapNumber.DestinationColumn = "ProdNum"; - bulkCopy.ColumnMappings.Add(mapNumber); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs b/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs deleted file mode 100644 index 19e31f282d..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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 source and destination. - SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(); - mapID.SourceOrdinal = 0; - mapID.DestinationOrdinal = 0; - bulkCopy.ColumnMappings.Add(mapID); - - SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping(); - mapName.SourceOrdinal = 1; - mapName.DestinationOrdinal = 2; - bulkCopy.ColumnMappings.Add(mapName); - - SqlBulkCopyColumnMapping mapNumber = new SqlBulkCopyColumnMapping(); - mapNumber.SourceOrdinal = 2; - mapNumber.DestinationOrdinal = 1; - bulkCopy.ColumnMappings.Add(mapNumber); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs b/doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs deleted file mode 100644 index fa0db0ef4c..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs b/doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs deleted file mode 100644 index bdda864974..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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 and ordinal. - SqlBulkCopyColumnMapping columnMapID = - new SqlBulkCopyColumnMapping("ProductID", 0); - bulkCopy.ColumnMappings.Add(columnMapID); - - SqlBulkCopyColumnMapping columnMapName = - new SqlBulkCopyColumnMapping("Name", 2); - bulkCopy.ColumnMappings.Add(columnMapName); - - SqlBulkCopyColumnMapping columnMapNumber = - new SqlBulkCopyColumnMapping("ProductNumber", 1); - bulkCopy.ColumnMappings.Add(columnMapNumber); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs b/doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs deleted file mode 100644 index a488c621bc..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string connectionString = GetConnectionString(); - // Open a connection to the AdventureWorks database. - using (SqlConnection connection = - new SqlConnection(connectionString)) - { - connection.Open(); - - // Empty the destination tables. - SqlCommand deleteHeader = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderHeader;", - connection); - deleteHeader.ExecuteNonQuery(); - SqlCommand deleteDetail = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderDetail;", - connection); - deleteDetail.ExecuteNonQuery(); - - // Perform an initial count on the destination - // table with matching columns. - SqlCommand countRowHeader = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", - connection); - long countStartHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Header table = {0}", - countStartHeader); - - // Perform an initial count on the destination - // table with different column positions. - SqlCommand countRowDetail = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", - connection); - long countStartDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Detail table = {0}", - countStartDetail); - - // Get data from the source table as a SqlDataReader. - // The Sales.SalesOrderHeader and Sales.SalesOrderDetail - // tables are quite large and could easily cause a timeout - // if all data from the tables is added to the destination. - // To keep the example simple and quick, a parameter is - // used to select only orders for a particular account - // as the source for the bulk insert. - SqlCommand headerData = new SqlCommand( - "SELECT [SalesOrderID], [OrderDate], " + - "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + - "WHERE [AccountNumber] = @accountNumber;", - connection); - SqlParameter parameterAccount = new SqlParameter(); - parameterAccount.ParameterName = "@accountNumber"; - parameterAccount.SqlDbType = SqlDbType.NVarChar; - parameterAccount.Direction = ParameterDirection.Input; - parameterAccount.Value = "10-4020-000034"; - headerData.Parameters.Add(parameterAccount); - SqlDataReader readerHeader = headerData.ExecuteReader(); - - // Get the Detail data in a separate connection. - using (SqlConnection connection2 = new SqlConnection(connectionString)) - { - connection2.Open(); - SqlCommand sourceDetailData = new SqlCommand( - "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + - "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + - "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + - "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + - "WHERE [AccountNumber] = @accountNumber;", connection2); - - SqlParameter accountDetail = new SqlParameter(); - accountDetail.ParameterName = "@accountNumber"; - accountDetail.SqlDbType = SqlDbType.NVarChar; - accountDetail.Direction = ParameterDirection.Input; - accountDetail.Value = "10-4020-000034"; - sourceDetailData.Parameters.Add(accountDetail); - SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); - - // Create the SqlBulkCopy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoOrderHeader"; - - // Guarantee that columns are mapped correctly by - // defining the column mappings for the order. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); - bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); - - // Write readerHeader to the destination. - try - { - bulkCopy.WriteToServer(readerHeader); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerHeader.Close(); - } - - // Set up the order details destination. - bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; - - // Clear the ColumnMappingCollection. - bulkCopy.ColumnMappings.Clear(); - - // Add order detail column mappings. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); - bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); - bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); - bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); - - // Write readerDetail to the destination. - try - { - bulkCopy.WriteToServer(readerDetail); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerDetail.Close(); - } - } - - // Perform a final count on the destination - // tables to see how many rows were added. - long countEndHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Header table.", - countEndHeader - countStartHeader); - long countEndDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Detail table.", - countEndDetail - countStartDetail); - Console.WriteLine("Press Enter to finish."); - Console.ReadLine(); - } - } - } - - private static string GetConnectionString() - // To avoid storing the connection string in your code, - // you can retrieve it from a configuration file. - { - return "Data Source=(local); " + - " Integrated Security=true;" + - "Initial Catalog=AdventureWorks;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs b/doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs deleted file mode 100644 index 671383133f..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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 ordinal. - SqlBulkCopyColumnMapping columnMapID = - new SqlBulkCopyColumnMapping(0, 0); - bulkCopy.ColumnMappings.Add(columnMapID); - - SqlBulkCopyColumnMapping columnMapName = - new SqlBulkCopyColumnMapping(1, 2); - bulkCopy.ColumnMappings.Add(columnMapName); - - SqlBulkCopyColumnMapping columnMapNumber = - new SqlBulkCopyColumnMapping(2, 1); - bulkCopy.ColumnMappings.Add(columnMapNumber); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs b/doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs deleted file mode 100644 index 8ca91ee00e..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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 ordinal and name. - SqlBulkCopyColumnMapping columnMapID = - new SqlBulkCopyColumnMapping(0, "ProdID"); - bulkCopy.ColumnMappings.Add(columnMapID); - - SqlBulkCopyColumnMapping columnMapName = - new SqlBulkCopyColumnMapping(1, "ProdName"); - bulkCopy.ColumnMappings.Add(columnMapName); - - SqlBulkCopyColumnMapping columnMapNumber = - new SqlBulkCopyColumnMapping(2, "ProdNum"); - bulkCopy.ColumnMappings.Add(columnMapNumber); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingRemove.cs b/doc/samples/SqlBulkCopy_ColumnMappingRemove.cs deleted file mode 100644 index f5dc29e254..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingRemove.cs +++ /dev/null @@ -1,168 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string connectionString = GetConnectionString(); - // Open a connection to the AdventureWorks database. - using (SqlConnection connection = - new SqlConnection(connectionString)) - { - connection.Open(); - - // Empty the destination tables. - SqlCommand deleteHeader = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderHeader;", - connection); - deleteHeader.ExecuteNonQuery(); - SqlCommand deleteDetail = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderDetail;", - connection); - deleteDetail.ExecuteNonQuery(); - - // Perform an initial count on the destination - // table with matching columns. - SqlCommand countRowHeader = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", - connection); - long countStartHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Header table = {0}", - countStartHeader); - - // Perform an initial count on the destination - // table with different column positions. - SqlCommand countRowDetail = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", - connection); - long countStartDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Detail table = {0}", - countStartDetail); - - // Get data from the source table as a SqlDataReader. - // The Sales.SalesOrderHeader and Sales.SalesOrderDetail - // tables are quite large and could easily cause a timeout - // if all data from the tables is added to the destination. - // To keep the example simple and quick, a parameter is - // used to select only orders for a particular account - // as the source for the bulk insert. - SqlCommand headerData = new SqlCommand( - "SELECT [SalesOrderID], [OrderDate], " + - "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + - "WHERE [AccountNumber] = @accountNumber;", - connection); - SqlParameter parameterAccount = new SqlParameter(); - parameterAccount.ParameterName = "@accountNumber"; - parameterAccount.SqlDbType = SqlDbType.NVarChar; - parameterAccount.Direction = ParameterDirection.Input; - parameterAccount.Value = "10-4020-000034"; - headerData.Parameters.Add(parameterAccount); - SqlDataReader readerHeader = headerData.ExecuteReader(); - - // Get the Detail data in a separate connection. - using (SqlConnection connection2 = new SqlConnection(connectionString)) - { - connection2.Open(); - SqlCommand sourceDetailData = new SqlCommand( - "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + - "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + - "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + - "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + - "WHERE [AccountNumber] = @accountNumber;", connection2); - - SqlParameter accountDetail = new SqlParameter(); - accountDetail.ParameterName = "@accountNumber"; - accountDetail.SqlDbType = SqlDbType.NVarChar; - accountDetail.Direction = ParameterDirection.Input; - accountDetail.Value = "10-4020-000034"; - sourceDetailData.Parameters.Add(accountDetail); - SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); - - // Create the SqlBulkCopy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoOrderHeader"; - - // Guarantee that columns are mapped correctly by - // defining the column mappings for the order. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); - bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); - - // Write readerHeader to the destination. - try - { - bulkCopy.WriteToServer(readerHeader); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerHeader.Close(); - } - - // Set up the order details destination. - bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; - - // Clear the ColumnMappingCollection. - bulkCopy.ColumnMappings.Clear(); - - // Add order detail column mappings. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); - bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); - bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); - bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); - - // Write readerDetail to the destination. - try - { - bulkCopy.WriteToServer(readerDetail); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerDetail.Close(); - } - } - - // Perform a final count on the destination - // tables to see how many rows were added. - long countEndHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Header table.", - countEndHeader - countStartHeader); - long countEndDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Detail table.", - countEndDetail - countStartDetail); - Console.WriteLine("Press Enter to finish."); - Console.ReadLine(); - } - } - } - - private static string GetConnectionString() - // To avoid storing the connection string in your code, - // you can retrieve it from a configuration file. - { - return "Data Source=(local); " + - " Integrated Security=true;" + - "Initial Catalog=AdventureWorks;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs b/doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs deleted file mode 100644 index 9d8091965d..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs +++ /dev/null @@ -1,171 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string connectionString = GetConnectionString(); - // Open a connection to the AdventureWorks database. - using (SqlConnection connection = - new SqlConnection(connectionString)) - { - connection.Open(); - - // Empty the destination tables. - SqlCommand deleteHeader = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderHeader;", - connection); - deleteHeader.ExecuteNonQuery(); - SqlCommand deleteDetail = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderDetail;", - connection); - deleteDetail.ExecuteNonQuery(); - - // Perform an initial count on the destination - // table with matching columns. - SqlCommand countRowHeader = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", - connection); - long countStartHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Header table = {0}", - countStartHeader); - - // Perform an initial count on the destination - // table with different column positions. - SqlCommand countRowDetail = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", - connection); - long countStartDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Detail table = {0}", - countStartDetail); - - // Get data from the source table as a SqlDataReader. - // The Sales.SalesOrderHeader and Sales.SalesOrderDetail - // tables are quite large and could easily cause a timeout - // if all data from the tables is added to the destination. - // To keep the example simple and quick, a parameter is - // used to select only orders for a particular account - // as the source for the bulk insert. - SqlCommand headerData = new SqlCommand( - "SELECT [SalesOrderID], [OrderDate], " + - "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + - "WHERE [AccountNumber] = @accountNumber;", - connection); - SqlParameter parameterAccount = new SqlParameter(); - parameterAccount.ParameterName = "@accountNumber"; - parameterAccount.SqlDbType = SqlDbType.NVarChar; - parameterAccount.Direction = ParameterDirection.Input; - parameterAccount.Value = "10-4020-000034"; - headerData.Parameters.Add(parameterAccount); - SqlDataReader readerHeader = headerData.ExecuteReader(); - - // Get the Detail data in a separate connection. - using (SqlConnection connection2 = new SqlConnection(connectionString)) - { - connection2.Open(); - SqlCommand sourceDetailData = new SqlCommand( - "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + - "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + - "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + - "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + - "WHERE [AccountNumber] = @accountNumber;", connection2); - - SqlParameter accountDetail = new SqlParameter(); - accountDetail.ParameterName = "@accountNumber"; - accountDetail.SqlDbType = SqlDbType.NVarChar; - accountDetail.Direction = ParameterDirection.Input; - accountDetail.Value = "10-4020-000034"; - sourceDetailData.Parameters.Add(accountDetail); - SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); - - // Create the SqlBulkCopy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoOrderHeader"; - - // Guarantee that columns are mapped correctly by - // defining the column mappings for the order. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); - bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); - - // Write readerHeader to the destination. - try - { - bulkCopy.WriteToServer(readerHeader); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerHeader.Close(); - } - - // Set up the order details destination. - bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; - - // Rather than clearing mappings that are not necessary - // for the next bulk copyo peration, the unneeded mappings - // are removed with the RemoveAt method. - bulkCopy.ColumnMappings.RemoveAt(2); - bulkCopy.ColumnMappings.RemoveAt(1); - - // Add order detail column mappings. - bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); - bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); - bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); - bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); - bulkCopy.WriteToServer(readerDetail); - - // Write readerDetail to the destination. - try - { - bulkCopy.WriteToServer(readerDetail); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerDetail.Close(); - } - } - - // Perform a final count on the destination - // tables to see how many rows were added. - long countEndHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Header table.", - countEndHeader - countStartHeader); - long countEndDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Detail table.", - countEndDetail - countStartDetail); - Console.WriteLine("Press Enter to finish."); - Console.ReadLine(); - } - } - } - - private static string GetConnectionString() - // To avoid storing the connection string in your code, - // you can retrieve it from a configuration file. - { - return "Data Source=(local); " + - " Integrated Security=true;" + - "Initial Catalog=AdventureWorks;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHint.cs b/doc/samples/SqlBulkCopy_ColumnOrderHint.cs deleted file mode 100644 index 9960debf20..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnOrderHint.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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(); - - // Set up the bulk copy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - // Setup an order hint for the ProductNumber column. - SqlBulkCopyColumnOrderHint hintNumber = - new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); - bulkCopy.ColumnOrderHints.Add(hintNumber); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs deleted file mode 100644 index 4a92099ddb..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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(); - - // Set up the bulk copy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - // Specify the sort order for the ProductNumber column in - // the destination table. - bulkCopy.ColumnOrderHints.Add("ProductNumber", SortOrder.Ascending); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs deleted file mode 100644 index 2d6599d525..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs +++ /dev/null @@ -1,86 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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(); - - // Set up the bulk copy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - // Specify the sort order for the ProductNumber column in - // the destination table. - // Setup an order hint for the ProductNumber column. - SqlBulkCopyColumnOrderHint hintNumber = - new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); - bulkCopy.ColumnOrderHints.Add(hintNumber); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs deleted file mode 100644 index 4a92099ddb..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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(); - - // Set up the bulk copy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - // Specify the sort order for the ProductNumber column in - // the destination table. - bulkCopy.ColumnOrderHints.Add("ProductNumber", SortOrder.Ascending); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs deleted file mode 100644 index 0df1281b52..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs +++ /dev/null @@ -1,177 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string connectionString = GetConnectionString(); - // Open a connection to the AdventureWorks database. - using (SqlConnection connection = - new SqlConnection(connectionString)) - { - connection.Open(); - - // Empty the destination tables. - SqlCommand deleteHeader = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderHeader;", - connection); - deleteHeader.ExecuteNonQuery(); - SqlCommand deleteDetail = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderDetail;", - connection); - deleteDetail.ExecuteNonQuery(); - - // Perform an initial count on the destination - // table with matching columns. - SqlCommand countRowHeader = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", - connection); - long countStartHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Header table = {0}", - countStartHeader); - - // Perform an initial count on the destination - // table with different column positions. - SqlCommand countRowDetail = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", - connection); - long countStartDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Detail table = {0}", - countStartDetail); - - // Get data from the source table as a SqlDataReader. - // The Sales.SalesOrderHeader and Sales.SalesOrderDetail - // tables are quite large and could easily cause a timeout - // if all data from the tables is added to the destination. - // To keep the example simple and quick, a parameter is - // used to select only orders for a particular account - // as the source for the bulk insert. - SqlCommand headerData = new SqlCommand( - "SELECT [SalesOrderID], [OrderDate], " + - "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + - "WHERE [AccountNumber] = @accountNumber;", - connection); - SqlParameter parameterAccount = new SqlParameter(); - parameterAccount.ParameterName = "@accountNumber"; - parameterAccount.SqlDbType = SqlDbType.NVarChar; - parameterAccount.Direction = ParameterDirection.Input; - parameterAccount.Value = "10-4020-000034"; - headerData.Parameters.Add(parameterAccount); - SqlDataReader readerHeader = headerData.ExecuteReader(); - - // Get the Detail data in a separate connection. - using (SqlConnection connection2 = new SqlConnection(connectionString)) - { - connection2.Open(); - SqlCommand sourceDetailData = new SqlCommand( - "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + - "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + - "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + - "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + - "WHERE [AccountNumber] = @accountNumber;", connection2); - - SqlParameter accountDetail = new SqlParameter(); - accountDetail.ParameterName = "@accountNumber"; - accountDetail.SqlDbType = SqlDbType.NVarChar; - accountDetail.Direction = ParameterDirection.Input; - accountDetail.Value = "10-4020-000034"; - sourceDetailData.Parameters.Add(accountDetail); - SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); - - // Create the SqlBulkCopy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoOrderHeader"; - - // Guarantee that columns are mapped correctly by - // defining the column mappings for the order. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); - bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); - - // Add order hint for OrderDate column. - bulkCopy.ColumnOrderHints.Add("OrderDate", SortOrder.Ascending); - - // Write readerHeader to the destination. - try - { - bulkCopy.WriteToServer(readerHeader); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerHeader.Close(); - } - - // Set up the order details destination. - bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; - - // Clear the ColumnMappingCollection. - bulkCopy.ColumnMappings.Clear(); - - // Add order detail column mappings. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); - bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); - bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); - bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); - - // Clear the ColumnOrderHintCollection. - bulkCopy.ColumnOrderHints.Clear(); - - // Add order hint for SalesOrderID column. - bulkCopy.ColumnOrderHints.Add("SalesOrderID", SortOrder.Ascending); - - // Write readerDetail to the destination. - try - { - bulkCopy.WriteToServer(readerDetail); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerDetail.Close(); - } - } - - // Perform a final count on the destination - // tables to see how many rows were added. - long countEndHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Header table.", - countEndHeader - countStartHeader); - long countEndDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Detail table.", - countEndDetail - countStartDetail); - Console.WriteLine("Press Enter to finish."); - Console.ReadLine(); - } - } - } - - private static string GetConnectionString() - // To avoid storing the connection string in your code, - // you can retrieve it from a configuration file. - { - return "Data Source=(local); " + - " Integrated Security=true;" + - "Initial Catalog=AdventureWorks;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs deleted file mode 100644 index ea9a8f4a46..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs +++ /dev/null @@ -1,176 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string connectionString = GetConnectionString(); - // Open a connection to the AdventureWorks database. - using (SqlConnection connection = - new SqlConnection(connectionString)) - { - connection.Open(); - - // Empty the destination tables. - SqlCommand deleteHeader = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderHeader;", - connection); - deleteHeader.ExecuteNonQuery(); - SqlCommand deleteDetail = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderDetail;", - connection); - deleteDetail.ExecuteNonQuery(); - - // Perform an initial count on the destination - // table with matching columns. - SqlCommand countRowHeader = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", - connection); - long countStartHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Header table = {0}", - countStartHeader); - - // Perform an initial count on the destination - // table with different column positions. - SqlCommand countRowDetail = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", - connection); - long countStartDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Detail table = {0}", - countStartDetail); - - // Get data from the source table as a SqlDataReader. - // The Sales.SalesOrderHeader and Sales.SalesOrderDetail - // tables are quite large and could easily cause a timeout - // if all data from the tables is added to the destination. - // To keep the example simple and quick, a parameter is - // used to select only orders for a particular account - // as the source for the bulk insert. - SqlCommand headerData = new SqlCommand( - "SELECT [SalesOrderID], [OrderDate], " + - "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + - "WHERE [AccountNumber] = @accountNumber;", - connection); - SqlParameter parameterAccount = new SqlParameter(); - parameterAccount.ParameterName = "@accountNumber"; - parameterAccount.SqlDbType = SqlDbType.NVarChar; - parameterAccount.Direction = ParameterDirection.Input; - parameterAccount.Value = "10-4020-000034"; - headerData.Parameters.Add(parameterAccount); - SqlDataReader readerHeader = headerData.ExecuteReader(); - - // Get the Detail data in a separate connection. - using (SqlConnection connection2 = new SqlConnection(connectionString)) - { - connection2.Open(); - SqlCommand sourceDetailData = new SqlCommand( - "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + - "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + - "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + - "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + - "WHERE [AccountNumber] = @accountNumber;", connection2); - - SqlParameter accountDetail = new SqlParameter(); - accountDetail.ParameterName = "@accountNumber"; - accountDetail.SqlDbType = SqlDbType.NVarChar; - accountDetail.Direction = ParameterDirection.Input; - accountDetail.Value = "10-4020-000034"; - sourceDetailData.Parameters.Add(accountDetail); - SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); - - // Create the SqlBulkCopy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoOrderHeader"; - - // Guarantee that columns are mapped correctly by - // defining the column mappings for the order. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); - bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); - - // Add the order hint for the OrderDate column. - SqlBulkCopyColumnOrderHint hintDate = - new SqlBulkCopyColumnOrderHint("OrderDate", SortOrder.Ascending); - bulkCopy.ColumnOrderHints.Add(hintDate); - - // Write readerHeader to the destination. - try - { - bulkCopy.WriteToServer(readerHeader); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerHeader.Close(); - } - - // Set up the order details destination. - bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; - - // Clear the ColumnMappingCollection. - bulkCopy.ColumnMappings.Clear(); - - // Add order detail column mappings. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); - bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); - bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); - bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); - - // Remove the order hint for the OrderDate column. - bulkCopy.ColumnOrderHints.Remove(hintDate); - - // Write readerDetail to the destination. - try - { - bulkCopy.WriteToServer(readerDetail); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerDetail.Close(); - } - } - - // Perform a final count on the destination - // tables to see how many rows were added. - long countEndHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Header table.", - countEndHeader - countStartHeader); - long countEndDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Detail table.", - countEndDetail - countStartDetail); - Console.WriteLine("Press Enter to finish."); - Console.ReadLine(); - } - } - } - - private static string GetConnectionString() - // To avoid storing the connection string in your code, - // you can retrieve it from a configuration file. - { - return "Data Source=(local); " + - " Integrated Security=true;" + - "Initial Catalog=AdventureWorks;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs deleted file mode 100644 index b965599175..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs +++ /dev/null @@ -1,176 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string connectionString = GetConnectionString(); - // Open a connection to the AdventureWorks database. - using (SqlConnection connection = - new SqlConnection(connectionString)) - { - connection.Open(); - - // Empty the destination tables. - SqlCommand deleteHeader = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderHeader;", - connection); - deleteHeader.ExecuteNonQuery(); - SqlCommand deleteDetail = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderDetail;", - connection); - deleteDetail.ExecuteNonQuery(); - - // Perform an initial count on the destination - // table with matching columns. - SqlCommand countRowHeader = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", - connection); - long countStartHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Header table = {0}", - countStartHeader); - - // Perform an initial count on the destination - // table with different column positions. - SqlCommand countRowDetail = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", - connection); - long countStartDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Detail table = {0}", - countStartDetail); - - // Get data from the source table as a SqlDataReader. - // The Sales.SalesOrderHeader and Sales.SalesOrderDetail - // tables are quite large and could easily cause a timeout - // if all data from the tables is added to the destination. - // To keep the example simple and quick, a parameter is - // used to select only orders for a particular account - // as the source for the bulk insert. - SqlCommand headerData = new SqlCommand( - "SELECT [SalesOrderID], [OrderDate], " + - "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + - "WHERE [AccountNumber] = @accountNumber;", - connection); - SqlParameter parameterAccount = new SqlParameter(); - parameterAccount.ParameterName = "@accountNumber"; - parameterAccount.SqlDbType = SqlDbType.NVarChar; - parameterAccount.Direction = ParameterDirection.Input; - parameterAccount.Value = "10-4020-000034"; - headerData.Parameters.Add(parameterAccount); - SqlDataReader readerHeader = headerData.ExecuteReader(); - - // Get the Detail data in a separate connection. - using (SqlConnection connection2 = new SqlConnection(connectionString)) - { - connection2.Open(); - SqlCommand sourceDetailData = new SqlCommand( - "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + - "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + - "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + - "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + - "WHERE [AccountNumber] = @accountNumber;", connection2); - - SqlParameter accountDetail = new SqlParameter(); - accountDetail.ParameterName = "@accountNumber"; - accountDetail.SqlDbType = SqlDbType.NVarChar; - accountDetail.Direction = ParameterDirection.Input; - accountDetail.Value = "10-4020-000034"; - sourceDetailData.Parameters.Add(accountDetail); - SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); - - // Create the SqlBulkCopy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoOrderHeader"; - - // Guarantee that columns are mapped correctly by - // defining the column mappings for the order. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); - bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); - - // Add the order hint for the OrderDate column. - SqlBulkCopyColumnOrderHint hintDate = - new SqlBulkCopyColumnOrderHint("OrderDate", SortOrder.Ascending); - bulkCopy.ColumnOrderHints.Add(hintDate); - - // Write readerHeader to the destination. - try - { - bulkCopy.WriteToServer(readerHeader); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerHeader.Close(); - } - - // Set up the order details destination. - bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; - - // Clear the ColumnMappingCollection. - bulkCopy.ColumnMappings.Clear(); - - // Add order detail column mappings. - bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); - bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); - bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); - bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); - bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); - - // Remove the order hint for the OrderDate column. - bulkCopy.ColumnOrderHints.RemoveAt(0); - - // Write readerDetail to the destination. - try - { - bulkCopy.WriteToServer(readerDetail); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerDetail.Close(); - } - } - - // Perform a final count on the destination - // tables to see how many rows were added. - long countEndHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Header table.", - countEndHeader - countStartHeader); - long countEndDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Detail table.", - countEndDetail - countStartDetail); - Console.WriteLine("Press Enter to finish."); - Console.ReadLine(); - } - } - } - - private static string GetConnectionString() - // To avoid storing the connection string in your code, - // you can retrieve it from a configuration file. - { - return "Data Source=(local); " + - " Integrated Security=true;" + - "Initial Catalog=AdventureWorks;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs deleted file mode 100644 index 6a75e0289c..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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(); - - // Set up the bulk copy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - // Setup an order hint for the ProductNumber column. - SqlBulkCopyColumnOrderHint hintNumber = - new SqlBulkCopyColumnOrderHint("number", SortOrder.Ascending); - hintNumber.Column = "ProductNumber"; - bulkCopy.ColumnOrderHints.Add(hintNumber); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs deleted file mode 100644 index 54cef5da53..0000000000 --- a/doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -using System; -using System.Data; -using Microsoft.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(); - - // Set up the bulk copy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - // Setup an order hint for the ProductNumber column. - SqlBulkCopyColumnOrderHint hintNumber = - new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); - hintNumber.SortOrder = SortOrder.Descending; - bulkCopy.ColumnOrderHints.Add(hintNumber); - - // 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_ConnectionString.cs b/doc/samples/SqlBulkCopy_ConnectionString.cs deleted file mode 100644 index 50c3101369..0000000000 --- a/doc/samples/SqlBulkCopy_ConnectionString.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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(); - - // Set up the bulk copy object using a connection string. - // 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)) - { - 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_DataTable.cs b/doc/samples/SqlBulkCopy_DataTable.cs deleted file mode 100644 index a3c8c98fae..0000000000 --- a/doc/samples/SqlBulkCopy_DataTable.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string connectionString = GetConnectionString(); - // Open a connection to the AdventureWorks database. - using (SqlConnection connection = - new SqlConnection(connectionString)) - { - connection.Open(); - - // Perform an initial count on the destination table. - SqlCommand commandRowCount = new SqlCommand( - "SELECT COUNT(*) FROM " + - "dbo.BulkCopyDemoMatchingColumns;", - connection); - long countStart = System.Convert.ToInt32( - commandRowCount.ExecuteScalar()); - Console.WriteLine("Starting row count = {0}", countStart); - - // Create a table with some rows. - DataTable newProducts = MakeTable(); - - // Create the SqlBulkCopy object. - // Note that the column positions in the source DataTable - // match the column positions in the destination table so - // there is no need to map columns. - using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - try - { - // Write from the source to the destination. - bulkCopy.WriteToServer(newProducts); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - } - - // 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 DataTable MakeTable() - // Create a new DataTable named NewProducts. - { - DataTable newProducts = new DataTable("NewProducts"); - - // Add three column objects to the table. - DataColumn productID = new DataColumn(); - productID.DataType = System.Type.GetType("System.Int32"); - productID.ColumnName = "ProductID"; - productID.AutoIncrement = true; - newProducts.Columns.Add(productID); - - DataColumn productName = new DataColumn(); - productName.DataType = System.Type.GetType("System.String"); - productName.ColumnName = "Name"; - newProducts.Columns.Add(productName); - - DataColumn productNumber = new DataColumn(); - productNumber.DataType = System.Type.GetType("System.String"); - productNumber.ColumnName = "ProductNumber"; - newProducts.Columns.Add(productNumber); - - // Create an array for DataColumn objects. - DataColumn[] keys = new DataColumn[1]; - keys[0] = productID; - newProducts.PrimaryKey = keys; - - // Add some new rows to the collection. - DataRow row = newProducts.NewRow(); - row["Name"] = "CC-101-WH"; - row["ProductNumber"] = "Cyclocomputer - White"; - - newProducts.Rows.Add(row); - row = newProducts.NewRow(); - row["Name"] = "CC-101-BK"; - row["ProductNumber"] = "Cyclocomputer - Black"; - - newProducts.Rows.Add(row); - row = newProducts.NewRow(); - row["Name"] = "CC-101-ST"; - row["ProductNumber"] = "Cyclocomputer - Stainless"; - newProducts.Rows.Add(row); - newProducts.AcceptChanges(); - - // Return the new DataTable. - return newProducts; - } - private static string GetConnectionString() - // To avoid storing the connection string in your code, - // you can retrieve it from a configuration file. - { - return "Data Source=(local); " + - " Integrated Security=true;" + - "Initial Catalog=AdventureWorks;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_KeepIdentity.cs b/doc/samples/SqlBulkCopy_KeepIdentity.cs deleted file mode 100644 index da85715725..0000000000 --- a/doc/samples/SqlBulkCopy_KeepIdentity.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_NotifyAfter.cs b/doc/samples/SqlBulkCopy_NotifyAfter.cs deleted file mode 100644 index fb01bb9a5c..0000000000 --- a/doc/samples/SqlBulkCopy_NotifyAfter.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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("NotifyAfter Sample"); - 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. - // 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)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - // Set up the event handler to notify after 50 rows. - bulkCopy.SqlRowsCopied += - new SqlRowsCopiedEventHandler(OnSqlRowsCopied); - bulkCopy.NotifyAfter = 50; - - 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 void OnSqlRowsCopied( - object sender, SqlRowsCopiedEventArgs e) - { - Console.WriteLine("Copied {0} so far...", e.RowsCopied); - } - 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;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_OrdersDetails.cs b/doc/samples/SqlBulkCopy_OrdersDetails.cs deleted file mode 100644 index 9fd713a548..0000000000 --- a/doc/samples/SqlBulkCopy_OrdersDetails.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string connectionString = GetConnectionString(); - // Open a connection to the AdventureWorks database. - using (SqlConnection connection = - new SqlConnection(connectionString)) - { - connection.Open(); - - // Empty the destination tables. - SqlCommand deleteHeader = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderHeader;", - connection); - deleteHeader.ExecuteNonQuery(); - SqlCommand deleteDetail = new SqlCommand( - "DELETE FROM dbo.BulkCopyDemoOrderDetail;", - connection); - deleteDetail.ExecuteNonQuery(); - - // Perform an initial count on the destination - // table with matching columns. - SqlCommand countRowHeader = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", - connection); - long countStartHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Header table = {0}", - countStartHeader); - - // Perform an initial count on the destination - // table with different column positions. - SqlCommand countRowDetail = new SqlCommand( - "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", - connection); - long countStartDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Detail table = {0}", - countStartDetail); - - // Get data from the source table as a SqlDataReader. - // The Sales.SalesOrderHeader and Sales.SalesOrderDetail - // tables are quite large and could easily cause a timeout - // if all data from the tables is added to the destination. - // To keep the example simple and quick, a parameter is - // used to select only orders for a particular account - // as the source for the bulk insert. - SqlCommand headerData = new SqlCommand( - "SELECT [SalesOrderID], [OrderDate], " + - "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + - "WHERE [AccountNumber] = @accountNumber;", - connection); - SqlParameter parameterAccount = new SqlParameter(); - parameterAccount.ParameterName = "@accountNumber"; - parameterAccount.SqlDbType = SqlDbType.NVarChar; - parameterAccount.Direction = ParameterDirection.Input; - parameterAccount.Value = "10-4020-000034"; - headerData.Parameters.Add(parameterAccount); - SqlDataReader readerHeader = headerData.ExecuteReader(); - - // Get the Detail data in a separate connection. - using (SqlConnection connection2 = new SqlConnection(connectionString)) - { - connection2.Open(); - SqlCommand sourceDetailData = new SqlCommand( - "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + - "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + - "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + - "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + - "WHERE [AccountNumber] = @accountNumber;", connection2); - - SqlParameter accountDetail = new SqlParameter(); - accountDetail.ParameterName = "@accountNumber"; - accountDetail.SqlDbType = SqlDbType.NVarChar; - accountDetail.Direction = ParameterDirection.Input; - accountDetail.Value = "10-4020-000034"; - sourceDetailData.Parameters.Add(accountDetail); - SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); - - // Create the SqlBulkCopy object. - using (SqlBulkCopy bulkCopy = - new SqlBulkCopy(connectionString)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoOrderHeader"; - - // Write readerHeader to the destination. - try - { - bulkCopy.WriteToServer(readerHeader); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerHeader.Close(); - } - - // Set up a different destination and - // map columns. - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoOrderDetail"; - - // Write readerDetail to the destination. - try - { - bulkCopy.WriteToServer(readerDetail); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - finally - { - readerDetail.Close(); - } - } - - // Perform a final count on the destination - // tables to see how many rows were added. - long countEndHeader = System.Convert.ToInt32( - countRowHeader.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Header table.", - countEndHeader - countStartHeader); - long countEndDetail = System.Convert.ToInt32( - countRowDetail.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Detail table.", - countEndDetail - countStartDetail); - Console.WriteLine("Press Enter to finish."); - Console.ReadLine(); - } - } - } - - private static string GetConnectionString() - // To avoid storing the connection string in your code, - // you can retrieve it from a configuration file. - { - return "Data Source=(local); " + - " Integrated Security=true;" + - "Initial Catalog=AdventureWorks;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_RowArray.cs b/doc/samples/SqlBulkCopy_RowArray.cs deleted file mode 100644 index cce09d0233..0000000000 --- a/doc/samples/SqlBulkCopy_RowArray.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - string connectionString = GetConnectionString(); - // Open a connection to the AdventureWorks database. - using (SqlConnection connection = - new SqlConnection(connectionString)) - { - connection.Open(); - - // Perform an initial count on the destination table. - SqlCommand commandRowCount = new SqlCommand( - "SELECT COUNT(*) FROM " + - "dbo.BulkCopyDemoMatchingColumns;", - connection); - long countStart = System.Convert.ToInt32( - commandRowCount.ExecuteScalar()); - Console.WriteLine("Starting row count = {0}", countStart); - - // Create a table with some rows. - DataTable newProducts = MakeTable(); - - // Get a reference to a single row in the table. - DataRow[] rowArray = newProducts.Select( - "Name='CC-101-BK'"); - - // Create the SqlBulkCopy object. - // Note that the column positions in the source DataTable - // match the column positions in the destination table so - // there is no need to map columns. - using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) - { - bulkCopy.DestinationTableName = - "dbo.BulkCopyDemoMatchingColumns"; - - try - { - // Write the array of rows to the destination. - bulkCopy.WriteToServer(rowArray); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - } - - // 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 DataTable MakeTable() - // Create a new DataTable named NewProducts. - { - DataTable newProducts = new DataTable("NewProducts"); - - // Add three column objects to the table. - DataColumn productID = new DataColumn(); - productID.DataType = System.Type.GetType("System.Int32"); - productID.ColumnName = "ProductID"; - productID.AutoIncrement = true; - newProducts.Columns.Add(productID); - - DataColumn productName = new DataColumn(); - productName.DataType = System.Type.GetType("System.String"); - productName.ColumnName = "Name"; - newProducts.Columns.Add(productName); - - DataColumn productNumber = new DataColumn(); - productNumber.DataType = System.Type.GetType("System.String"); - productNumber.ColumnName = "ProductNumber"; - newProducts.Columns.Add(productNumber); - - // Create an array for DataColumn objects. - DataColumn[] keys = new DataColumn[1]; - keys[0] = productID; - newProducts.PrimaryKey = keys; - - // Add some new rows to the collection. - DataRow row = newProducts.NewRow(); - row["Name"] = "CC-101-WH"; - row["ProductNumber"] = "Cyclocomputer - White"; - - newProducts.Rows.Add(row); - row = newProducts.NewRow(); - row["Name"] = "CC-101-BK"; - row["ProductNumber"] = "Cyclocomputer - Black"; - - newProducts.Rows.Add(row); - row = newProducts.NewRow(); - row["Name"] = "CC-101-ST"; - row["ProductNumber"] = "Cyclocomputer - Stainless"; - newProducts.Rows.Add(row); - newProducts.AcceptChanges(); - - // Return the new DataTable. - return newProducts; - } - private static string GetConnectionString() - // To avoid storing the connection string in your code, - // you can retrieve it from a configuration file. - { - return "Data Source=(local); " + - " Integrated Security=true;" + - "Initial Catalog=AdventureWorks;"; - } -} -// diff --git a/doc/samples/SqlBulkCopy_Single.cs b/doc/samples/SqlBulkCopy_Single.cs deleted file mode 100644 index e5b7f7538e..0000000000 --- a/doc/samples/SqlBulkCopy_Single.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Data; -// -using Microsoft.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;"; - } -} -// diff --git a/doc/samples/SqlClientFactory_DataSourceEnumerator.cs b/doc/samples/SqlClientFactory_DataSourceEnumerator.cs deleted file mode 100644 index f1e1a09992..0000000000 --- a/doc/samples/SqlClientFactory_DataSourceEnumerator.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -using System; -using System.Data; -using System.Data.Common; -using Microsoft.Data.SqlClient; - -class Program -{ - static void Main() - { - // List all SQL Server instances: - ListServers(SqlClientFactory.Instance); - - Console.WriteLine(); - Console.WriteLine("Press any key to continue..."); - Console.ReadKey(); - } - private static void ListServers(DbProviderFactory factory) - { - // This procedure is provider-agnostic, and can list - // instances of any provider's servers. Of course, - // not all providers can create a data source enumerator, - // so it's best to check the CanCreateDataSourceEnumerator - // property before attempting to list the data sources. - if (factory.CanCreateDataSourceEnumerator) - { - DbDataSourceEnumerator instance = - factory.CreateDataSourceEnumerator(); - DataTable table = instance.GetDataSources(); - - foreach (DataRow row in table.Rows) - { - Console.WriteLine("{0}\\{1}", - row["ServerName"], row["InstanceName"]); - } - } - } -} -// diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommand.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommand.xml index be3744d730..cfce5cfce9 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommand.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommand.xml @@ -1,34 +1,89 @@ - - + - SqlBatchCommand allows for the execution of multiple SQL commands in a SqlBatch. - + SqlBatchCommand allows for the execution of multiple SQL commands in a SqlBatch. + - Initializes a new . - - - and a SqlBatch, then adds multiple objects to the batch. It then executes the batch, creating a . The example reads through the results of the batch commands, writing them to the console. Finally, the example closes the and then the as the `using` blocks fall out of scope. + + Initializes a new . + + + The following example creates a and a SqlBatch, then adds multiple objects to the batch. It then executes the batch, creating a . The example reads through the results of the batch commands, writing them to the console. Finally, the example closes the and then the as the using blocks fall out of scope. + + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string str = "Data Source=(local);Initial Catalog=Northwind;" + + "Integrated Security=SSPI;Encrypt=False"; + RunBatch(str); + } + + static void RunBatch(string connString) + { + using var connection = new SqlConnection(connString); + connection.Open(); + + var batch = new SqlBatch(connection); + + const int count = 10; + const string parameterName = "parameter"; + for (int i = 0; i < count; i++) + { + var batchCommand = new SqlBatchCommand($"SELECT @{parameterName} as value"); + batchCommand.Parameters.Add(new SqlParameter(parameterName, i)); + batch.BatchCommands.Add(batchCommand); + } + + // Optionally Prepare + batch.Prepare(); -[!code-csharp[SqlCommand Example#1](~/../sqlclient/doc/samples/SqlBatch_ExecuteReader.cs#1)] -]]> - - + var results = new List<int>(count); + using (SqlDataReader reader = batch.ExecuteReader()) + { + do + { + while (reader.Read()) + { + results.Add(reader.GetFieldValue<int>(0)); + } + } while (reader.NextResult()); + } + Console.WriteLine(string.Join(", ", results)); + } + } + + + - Initializes a new . - The text of the . - Indicates how the property is to be interpreted. - A collection of objects is used to create the . - The encryption setting. For more information, see [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine). + + Initializes a new . + + + The text of the . + + + Indicates how the property is to be interpreted. + + + A collection of objects is used to create the . + + + The encryption setting. For more information, see Always Encrypted. + - Gets the . - The parameters of the Transact-SQL statement or stored procedure. The default is an empty collection. + + Gets the . + + + The parameters of the Transact-SQL statement or stored procedure. The default is an empty collection. + @@ -38,28 +93,42 @@ The following example creates a an Not currently implemented. - The encryption setting. For more information, see [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine). + The encryption setting. For more information, see Always Encrypted. - Creates a new instance of a object. + + Creates a new instance of a object. + - Returns whether the method is implemented. + Returns whether the method is implemented. - Gets or sets the text command to run against the data source. - The text command to execute. The default value is an empty string (""). + + Gets or sets the text command to run against the data source. + + + The text command to execute. The default value is an empty string (""). + - Gets or sets how the property is interpreted. - One of the enumeration values that specifies how a command string is interpreted. The default is . + + Gets or sets how the property is interpreted. + + + One of the enumeration values that specifies how a command string is interpreted. The default is . + - Gets the collection of objects. - The parameters of the SQL statement or stored procedure. + + Gets the collection of objects. + + + The parameters of the SQL statement or stored procedure. + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml index ca089e9712..c5413e2194 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml @@ -1,20 +1,14 @@ - - + - A collection of instances of - , contained within a - . + A collection of instances of , contained within a . - Add a - to the end of the - . + Add a to the end of the . - @@ -22,16 +16,12 @@ Adds the specified object to the . - - To be added. + - Determines whether a - is in the - . + Determines whether a is in the . - @@ -43,13 +33,11 @@ if the is in the collection; otherwise . - To be added. Copies the entire to a one dimensional array, starting at the target index of the target array. - @@ -61,7 +49,6 @@ Copies the elements of the to an , starting at a particular index. - To be added. @@ -81,13 +68,11 @@ The index of the specified object. - To be added. - + Inserts an item into the at the specified index. - @@ -99,7 +84,6 @@ Inserts the specified index of the object with the specified name into the collection at the specified index. - To be added. @@ -111,25 +95,30 @@ - The object to remove from the . + The object to remove from the . Removes the specified object from the collection. if was successfully removed; otherwise, . This method also returns if was not found in the . - - To be added. + - Gets or Sets the element at the specified index. - The element at the specified index. - + + Gets or Sets the element at the specified index. + + + The element at the specified index. + - Gets or Sets the element at the specified index. - The element at the specified index. - + + Gets or Sets the element at the specified index. + + + The element at the specified index. + @@ -146,31 +135,46 @@ The index where the object should be located. - To be added. Sets the object at the specified index to a new value. - To be added. - Gets the number of elements contained in the . - The number of elements contained in the . + + Gets the number of elements contained in the . + + + The number of elements contained in the . + - Specifies whether the collection is read-only. + + Specifies whether the collection is read-only. + - if the collection is read-only; otherwise . + if the collection is read-only; otherwise . + - Returns the object at the specified index in the collection. - The object at the specified index in the collection. + + Returns the object at the specified index in the collection. + + + The object at the specified index in the collection. + - Removes all values from the . + + Removes all values from the . + - The index where the object is located. - Removes the object at the specified index from the collection. + + The index where the object is located. + + + Removes the object at the specified index from the collection. + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml index 6f7cc400d5..2e75dbbd62 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml @@ -1,520 +1,1247 @@ - - - - - Lets you efficiently bulk load a SQL Server table with data from another source. - - - class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but offers a significant performance advantage over them. The class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a instance or read with a instance. will fail when bulk loading a column of type into a SQL Server column whose type is one of the date/time types added in SQL Server 2008. - -## Examples -The following console application demonstrates how to load data using the class. -In this example, a is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[BulkCopy.Single#1](~/../sqlclient/doc/samples/SqlBulkCopy_Single.cs#1)] -]]> - - - - - The already open - - instance that will be used to perform the bulk copy operation. If your connection string does not use - - , you can use - - to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. - - - Initializes a new instance of the - - class using the specified open instance of - - . - - - instance is initialized, the connection remains open after the instance is closed. -If the `connection` argument is null, an is thrown. - -## Examples -The following console application demonstrates how to bulk load data using a connection that is already open. In this example, a -is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database. This example is for demonstration -purposes only. You would not use `SqlBulkCopy` to move data from one table to another in the same database in a production application. -Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a -. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[BulkCopy.Single#1](~/../sqlclient/doc/samples/SqlBulkCopy_Single.cs#1)] -]]> - - - - - The already open - - instance that will be used to perform the bulk copy. If your connection string does not use - - , you can use - - to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. - - - A combination of values from the - - enumeration that determines which data source rows are copied to the destination table. - - - An existing - - instance under which the bulk copy will occur. - - - Initializes a new instance of the - - class using the supplied existing open instance of - - . The - - instance behaves according to options supplied in the - - parameter. If a non-null - - is supplied, the copy operations will be performed within that transaction. - - - - - - Performing Bulk Copy Operations - - - Overview of the SqlClient driver - - - - - The string defining the connection that will be opened for use by the - - instance. - If your connection string does not use - - , you can use - - or - - and - - to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. - - - Initializes and opens a new instance of - - based on the supplied - - . The constructor uses the - - to initialize a new instance of the - - class. - - - is thrown. If `connectionString` is an empty string, an is thrown. - -## Examples -The following console application demonstrates how to bulk load data by using a connection specified as a string. The connection is automatically -closed when the instance is closed. -In this example, the source data is first read from a SQL Server table to a instance. -The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ConnectionString#1](~/../sqlclient/doc/samples/SqlBulkCopy_ConnectionString.cs#1)] -]]> - - - If `connectionString` is an empty string, an - - is thrown. - - - - - The string defining the connection that will be opened for use by the - - instance. If your connection string does not use - - , you can use - - or - - and - - to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. - - - A combination of values from the - - enumeration that determines which data source rows are copied to the destination table. - - - Initializes and opens a new instance of - - based on the supplied - - . The constructor uses that - - to initialize a new instance of the - - class. The - - instance behaves according to options supplied in the - - parameter. - - - topic. - -## Examples -The following console application demonstrates how to perform a bulk load by using a connection specified as a string. -An option is set to use the value in the identity column of the source table when you load the destination table. In this example, -the source data is first read from a SQL Server table to a instance. -The source table and destination table each include an Identity column. By default, a new value for the **Identity** column is generated in the destination table for each row added. -In this example, an option is set when the connection is opened that forces the bulk load process to use the **Identity** values from the source table instead. -To see how the option changes the way the bulk load works, run the sample with the **dbo.BulkCopyDemoMatchingColumns** table empty. All rows load from the source. -Then run the sample again without emptying the table. An exception is thrown and the code writes a message to the console notifying you that rows weren't -added because of primary key constraint violations. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to -demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement -to copy the data. - -[!code-csharp[SqlBulkCopy.KeepIdentity#1](~/../sqlclient/doc/samples/SqlBulkCopy_KeepIdentity.cs#1)] -]]> - - - - - Number of rows in each batch. At the end of each batch, the rows in the batch are sent to the server. - - - The integer value of the - - property, or zero if no value has been set. - - - rows have been processed or there are no more rows to send to the destination data source. - -Zero (the default) indicates that each operation is a single batch. - -If the instance has been declared without the option in effect, -rows are sent to the server rows at a time, but no transaction-related action is taken. -If is in effect, each batch of rows is inserted as a separate transaction. - -The property can be set at any time. If a bulk copy is already in progress, the current batch is sized according to the previous batch size. -Subsequent batches use the new size. If the is initially zero and changed while a -operation is already in progress, that operation loads the data as a single batch. Any subsequent -operations on the same instance use the new . - -## Examples -The following console application demonstrates how to bulk load data in batches of 50 rows. For an example illustrating how -works with a transaction, see [Transaction and Bulk Copy Operations](/sql/connect/ado-net/sql/transaction-bulk-copy-operations). - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.BatchSize#1](~/../sqlclient/doc/samples/SqlBulkCopy_BatchSize.cs#1)] -]]> - - - - - Number of seconds for the operation to complete before it times out. - - - The integer value of the - - property. The default is 30 seconds. A value of 0 indicates no limit; the bulk copy will wait indefinitely. - - - instance. -The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.Timeout#1](~/../sqlclient/doc/samples/SqlBulkCopy_Timeout.cs#1)] -]]> - - - - - Closes the instance. - - - on the object, no other operation will succeed. Calls to the method will throw an . Calling the method from the event causes an to be thrown. -Note that open instances are closed implicitly at the end of a `using` block. - -## Examples -The following example uses the same instance to add sales orders and their associated details to two destination tables. Because the **AdventureWorks** sales order tables are large, the sample reads only orders placed by a certain account number and bulk copies those orders and details to the destination tables. The method is used only after both bulk copy operations are complete. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.OrdersDetails#1](~/../sqlclient/doc/samples/SqlBulkCopy_OrdersDetails.cs#1)] -]]> - - - - - Enables or disables a - - object to stream data from an - - object - - - - if a - - object can stream data from an - - object; otherwise, false. The default is - - . - - - is `true`, reads from an object using , -optimizing memory usage by using the streaming capabilities. Streaming is only applicable to max data types (i.e. -VARBINARY(MAX), VARCHAR(MAX), NVARCHAR(MAX), and XML). When is set to false, -the class loads all the data returned by the object into memory before sending it to the server. - -> [!NOTE] -> The main advantage of enabling streaming is reducing memory usage during bulk copy of max data types. -]]> - - - - - Returns a collection of - - items. Column mappings define the relationships between columns in the data source and columns in the destination. - - - A collection of column mappings. By default, it is an empty collection. - - - collection is unnecessary. However, if the column counts differ, -or the ordinal positions are not consistent, you must use to make sure that data is copied into the correct columns. - -During the execution of a bulk copy operation, this collection can be accessed, but it cannot be changed. Any attempt to change it will throw an . -]]> - - - - - Returns a collection of - - items. Column order hints describe the sort order of columns in the clustered index of the destination table. - - - A collection of column order hints. By default, it is an empty collection. - - - + + + + Lets you efficiently bulk load a SQL Server table with data from another source. + + + Microsoft SQL Server includes a popular command-prompt utility named bcp for moving data from one table to another, whether on a single server or between servers. The class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but offers a significant performance advantage over them. The class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a instance or read with a instance. will fail when bulk loading a column of type into a SQL Server column whose type is one of the date/time types added in SQL Server 2008. + + + The following console application demonstrates how to load data using the class. In this example, a is used to copy data from the Production.Product table in the SQL Server AdventureWorks database to a similar table in the same database. + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + The already open instance that will be used to perform the bulk copy operation. If your connection string does not use , you can use to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. + + + Initializes a new instance of the class using the specified open instance of . + + + Because the connection is already open when the instance is initialized, the connection remains open after the instance is closed. If the connection argument is null, an is thrown. + + + + The following console application demonstrates how to bulk load data using a connection that is already open. In this example, a is used to copy data from the Production.Product table in the SQL Server AdventureWorks database to a similar table in the same database. This example is for demonstration purposes only. You would not use SqlBulkCopy to move data from one table to another in the same database in a production application. Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + The already open instance that will be used to perform the bulk copy. If your connection string does not use , you can use to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. + + + A combination of values from the enumeration that determines which data source rows are copied to the destination table. + + + An existing instance under which the bulk copy will occur. + + + Initializes a new instance of the class using the supplied existing open instance of . The instance behaves according to options supplied in the parameter. If a non-null is supplied, the copy operations will be performed within that transaction. + + + If options include and the argument is not , an InvalidArgumentException is thrown. + + + For examples demonstrating how to use SqlBulkCopy in a transaction, see Transaction and Bulk Copy Operations. + + + Performing Bulk Copy Operations + + + Overview of the SqlClient driver + + + + + + The string defining the connection that will be opened for use by the instance. + + + If your connection string does not use , you can use or and to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. + + + + Initializes and opens a new instance of based on the supplied . The constructor uses the to initialize a new instance of the class. + + + The connection is automatically closed at the end of the bulk copy operation. If is , an is thrown. If is an empty string, an is thrown. + + + + The following console application demonstrates how to bulk load data by using a connection specified as a string. The connection is automatically closed when the instance is closed. In this example, the source data is first read from a SQL Server table to a instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.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(); + + // Set up the bulk copy object using a connection string. + // 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)) + { + 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;"; + } + } + + + + If is an empty string, an is thrown. + + + + + The string defining the connection that will be opened for use by the instance. If your connection string does not use , you can use or and to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string. + + + A combination of values from the enumeration that determines which data source rows are copied to the destination table. + + + Initializes and opens a new instance of based on the supplied . The constructor uses that to initialize a new instance of the class. The instance behaves according to options supplied in the parameter. + + + You can obtain detailed information about all the bulk copy options in the topic. + + + + The following console application demonstrates how to perform a bulk load by using a connection specified as a string. An option is set to use the value in the identity column of the source table when you load the destination table. In this example, the source data is first read from a SQL Server table to a instance. The source table and destination table each include an Identity column. By default, a new value for the Identity column is generated in the destination table for each row added. In this example, an option is set when the connection is opened that forces the bulk load process to use the Identity values from the source table instead. To see how the option changes the way the bulk load works, run the sample with the dbo.BulkCopyDemoMatchingColumns table empty. All rows load from the source. Then run the sample again without emptying the table. An exception is thrown and the code writes a message to the console notifying you that rows weren't added because of primary key constraint violations. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); -## Remarks -SqlBulkCopy's performance is improved if the data being imported is sorted according to the clustered index on the table, if any. -If the data is sorted in an order that differs from the order of a clustered index key or if there is no clustered index on the table, the order hint is ignored. -]]> - - - - - Name of the destination table on the server. - - - The string value of the - - property, or null if none as been supplied. - - - has not been set when is called, an -is thrown. If is modified while a operation is running, -the change does not affect the current operation. The new value is used the next time a method is called. - - is a three-part name (`..`). You can qualify the table name with its database and owning schema if you choose. -However, if the table name uses an underscore ("_") or any other special characters, you must escape the name using surrounding brackets as in (`[..]`). - -You can bulk-copy data to a temporary table by using a value such as `tempdb..#table` or `tempdb..#table` for the property. - -## Examples -The following console application demonstrates how to bulk load data using a connection that is already open. The destination table is a table in the **AdventureWorks** database. - -In this example, the connection is first used to read data from a SQL Server table to a instance. The source data does not have to -be located on SQL Server; you can use any data source that can be read to an or loaded to a . - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. -[!code-csharp[SqlBulkCopy.Single#1](~/../sqlclient/doc/samples/SqlBulkCopy_Single.cs#1)] -]]> - - - - - Defines the number of rows to be processed before generating a notification event. - - - The integer value of the - - property, or zero if the property has not been set. - - - property can be set at any time, even while a bulk copy operation is underway. Changes made during a bulk copy operation take effect after -the next notification. The new setting applies to all subsequent operations on the same instance. - -If is set to a number less than zero, an is thrown. - - -## Examples -The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that -the event handler is called after every 50 rows copied to the table. - -In this example, the connection is first used to read data from a SQL Server table to a instance. Then a second connection is opened to bulk copy the data. -Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to -demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` -statement to copy the data. - -[!code-csharp[SqlBulkCopy.NotifyAfter#1](~/../sqlclient/doc/samples/SqlBulkCopy_NotifyAfter.cs#1)] -]]> - - - - - Occurs every time that the number of rows specified by the - - property have been processed. - - - and are independent. Receipt of a - event does not imply that any rows have been sent to the server or committed. - -You cannot call SqlBulkCopy.Close () or SqlConnection.Close () from this event. -Doing this will cause an being thrown, and the object state will not change. If the user wants to cancel the -operation from the event, the property of the can be used. -(See [Transaction and Bulk Copy Operations](/sql/connect/ado-net/sql/transaction-bulk-copy-operations) for examples that use the - property.) - -No action, such as transaction activity, is supported in the connection during the execution of the bulk copy operation, and it is recommended that you not use the same connection used -during the event. However, you can open a different connection. - - -## Examples -The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that -the event handler is called after every 50 rows copied to the table. - -In this example, the connection is first used to read data from a SQL Server table to a instance. Note that the source data does not have to be located on -SQL Server; you can use any data source that can be read to an or loaded to a . - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier -and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.NotifyAfter#1](~/../sqlclient/doc/samples/SqlBulkCopy_NotifyAfter.cs#1)] -]]> - - - - - The number of rows processed in the ongoing bulk copy operation. - - - The integer value of the - - property. - - - - event and does not imply that this number of rows has been sent to the server or committed. - -This value can be accessed during or after the execution of a bulk copy operation. - -This value will wrap around and become negative if the number of rows exceeds int.MaxValue. Consider using the property. -]]> - - + // 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;"; + } + } + + + + + + Number of rows in each batch. At the end of each batch, the rows in the batch are sent to the server. + + + The integer value of the property, or zero if no value has been set. + + + + A batch is complete when rows have been processed or there are no more rows to send to the destination data source. + + + Zero (the default) indicates that each operation is a single batch. + + + If the instance has been declared without the option in effect, rows are sent to the server rows at a time, but no transaction-related action is taken. If is in effect, each batch of rows is inserted as a separate transaction. + + + The property can be set at any time. If a bulk copy is already in progress, the current batch is sized according to the previous batch size. Subsequent batches use the new size. If the is initially zero and changed while a operation is already in progress, that operation loads the data as a single batch. Any subsequent operations on the same instance use the new . + + + + + The following console application demonstrates how to bulk load data in batches of 50 rows. For an example illustrating how works with a transaction, see Transaction and Bulk Copy Operations. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using Microsoft.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. + // 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)) + { + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"; + + // Set the BatchSize. + bulkCopy.BatchSize = 50; + + 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;"; + } + } + + + + + + Number of seconds for the operation to complete before it times out. + + + The integer value of the property. The default is 30 seconds. A value of 0 indicates no limit; the bulk copy will wait indefinitely. + + + If the operation does time out, the transaction is not committed and all copied rows are removed from the destination table. + + + + The following console application demonstrates how to modify the time-out to 60 seconds when bulk loading data. In this example, the source data is first read from a SQL Server table to a instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.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. + // 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)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Set the timeout. + bulkCopy.BulkCopyTimeout = 60; + + 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;"; + } + } + + + + + + Closes the instance. + + + After you call on the object, no other operation will succeed. Calls to the method will throw an . Calling the method from the event causes an to be thrown. Note that open instances are closed implicitly at the end of a using block. + + + + The following example uses the same instance to add sales orders and their associated details to two destination tables. Because the AdventureWorks sales order tables are large, the sample reads only orders placed by a certain account number and bulk copies those orders and details to the destination tables. The method is used only after both bulk copy operations are complete. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", + connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderHeader"; + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up a different destination and + // map columns. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + + + Enables or disables a object to stream data from an object + + + if a object can stream data from an object; otherwise, false. The default is . + + + + When is , reads from an object using , optimizing memory usage by using the streaming capabilities. Streaming is only applicable to max data types (i.e. VARBINARY(MAX), VARCHAR(MAX), NVARCHAR(MAX), and XML). When is set to , the class loads all the data returned by the object into memory before sending it to the server. + + + The main advantage of enabling streaming is reducing memory usage during bulk copy of max data types. + + + + + + Returns a collection of items. Column mappings define the relationships between columns in the data source and columns in the destination. + + + A collection of column mappings. By default, it is an empty collection. + + + + If the data source and the destination table have the same number of columns, and the ordinal position of each source column within the data source matches the ordinal position of the corresponding destination column, the collection is unnecessary. However, if the column counts differ, or the ordinal positions are not consistent, you must use to make sure that data is copied into the correct columns. + + + During the execution of a bulk copy operation, this collection can be accessed, but it cannot be changed. Any attempt to change it will throw an . + + + + + + Returns a collection of items. Column order hints describe the sort order of columns in the clustered index of the destination table. + + + A collection of column order hints. By default, it is an empty collection. + + + SqlBulkCopy's performance is improved if the data being imported is sorted according to the clustered index on the table, if any. If the data is sorted in an order that differs from the order of a clustered index key or if there is no clustered index on the table, the order hint is ignored. + + + + + Name of the destination table on the server. + + + The string value of the property, or null if none as been supplied. + + + + If has not been set when is called, an is thrown. If is modified while a operation is running, the change does not affect the current operation. The new value is used the next time a method is called. + + + is a three-part name (<database>.<owningschema>.<name>). You can qualify the table name with its database and owning schema if you choose. However, if the table name uses an underscore ("_") or any other special characters, you must escape the name using surrounding brackets as in ([<database>.<owningschema>.<name_01>]). + + + You can bulk-copy data to a temporary table by using a value such as tempdb..#table or tempdb.<owner>.#table for the property. + + + + + The following console application demonstrates how to bulk load data using a connection that is already open. The destination table is a table in the AdventureWorks database. + + + In this example, the connection is first used to read data from a SQL Server table to a instance. The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + Defines the number of rows to be processed before generating a notification event. + + + The integer value of the property, or zero if the property has not been set. + + + + This property is designed for user interface components that illustrate the progress of a bulk copy operation. It indicates the number of rows to be processed before generating a notification event. The property can be set at any time, even while a bulk copy operation is underway. Changes made during a bulk copy operation take effect after the next notification. The new setting applies to all subsequent operations on the same instance. + + + If is set to a number less than zero, an is thrown. + + + + + The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that the event handler is called after every 50 rows copied to the table. + + + In this example, the connection is first used to read data from a SQL Server table to a instance. Then a second connection is opened to bulk copy the data. Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.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("NotifyAfter Sample"); + 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. + // 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)) + { + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"; + + // Set up the event handler to notify after 50 rows. + bulkCopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied); + bulkCopy.NotifyAfter = 50; + + 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 void OnSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) + { + Console.WriteLine("Copied {0} so far...", e.RowsCopied); + } + + 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;"; + } + } + + + + + + Occurs every time that the number of rows specified by the property have been processed. + + + + Note that the settings of and are independent. Receipt of a event does not imply that any rows have been sent to the server or committed. + + + You cannot call or from this event. Doing this will cause an being thrown, and the object state will not change. If the user wants to cancel the operation from the event, the property of the can be used. (See Transaction and Bulk Copy Operations for examples that use the property.) + + + No action, such as transaction activity, is supported in the connection during the execution of the bulk copy operation, and it is recommended that you not use the same connection used during the event. However, you can open a different connection. + + + + + The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that the event handler is called after every 50 rows copied to the table. + + + In this example, the connection is first used to read data from a SQL Server table to a instance. Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a . + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.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("NotifyAfter Sample"); + 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. + // 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)) + { + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"; + + // Set up the event handler to notify after 50 rows. + bulkCopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied); + bulkCopy.NotifyAfter = 50; + + 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 void OnSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) + { + Console.WriteLine("Copied {0} so far...", e.RowsCopied); + } + + 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;"; + } + } + + + + + + The number of rows processed in the ongoing bulk copy operation. + + + The integer value of the property. + + + + This value is incremented during the event and does not imply that this number of rows has been sent to the server or committed. + + + This value can be accessed during or after the execution of a bulk copy operation. + + + This value will wrap around and become negative if the number of rows exceeds int.MaxValue. Consider using the property. + + + The number of rows processed in the ongoing bulk copy operation. @@ -523,872 +1250,915 @@ This value will wrap around and become negative if the number of rows exceeds in The long value of the property. - - event and does not imply that this number of rows has been sent to the server or committed. - -This value can be accessed during or after the execution of a bulk copy operation. -]]> - + + This value is incremented during the event and does not imply that this number of rows has been sent to the server or committed. + + + This value can be accessed during or after the execution of a bulk copy operation. + - - - Releases all resources used by the current instance of the - - class. - - - . The `Dispose` method leaves the in an unusable state. -After calling `Dispose`, you must release all references to the so the garbage collector can reclaim the memory that the - was occupying. - -For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and -[Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - -> [!NOTE] -> Always call `Dispose` before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls -the object's `Finalize` method. -]]> - - - - - A - - whose rows will be copied to the destination table. - - - Copies all rows from the supplied - - array to a destination table specified by the - - property of the - - object. - - - To be added. - - - A - - did not specify a valid destination column name. - - - - - A - - whose rows will be copied to the destination table. - - - Copies all rows in the supplied - - to a destination table specified by the - - property of the - - object. - - - or a similar call, -so the next available row is the first row. To process multiple results, call on the data reader and call - again. - -Note that using modifies the state of the reader. The method will call -until it returns false, the operation is aborted, or an error occurs. This means that the data reader will be in a different state, probably at the end of the result set, -when the operation is complete. - -While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. - -The collection maps from the data reader columns to the destination database table. - -## Examples -The following console application demonstrates how to bulk load data from a . The destination table is a table in the **AdventureWorks** database. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided -to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ConnectionString#1](~/../sqlclient/doc/samples/SqlBulkCopy_ConnectionString.cs#1)] -]]> - - - A - - did not specify a valid destination column name. - - - - - A - - whose rows will be copied to the destination table. - - - Copies all rows in the supplied - - to a destination table specified by the - - property of the - - object. - - - are copied to the destination table except those that have been deleted. - -While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. - -The collection maps from the columns to the destination database table. - -## Examples -The following Console application demonstrates how to bulk load data from a . The destination table is a table in the **AdventureWorks** database. - -In this example, a is created at run time and is the source of the `SqlBulkCopy` operation. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.DataTable#1](~/../sqlclient/doc/samples/SqlBulkCopy_DataTable.cs#1)] -]]> - - - A - - did not specify a valid destination column name. - - - Performing Bulk Copy Operations - - - Overview of the SqlClient driver - - - - - A - - whose rows will be copied to the destination table. - - - A value from the - - enumeration. Only rows matching the row state are copied to the destination. - - - Copies only rows that match the supplied row state in the supplied - - to a destination table specified by the - - property of the - - object. - - - that are in the states indicated in the `rowState` argument and have not been deleted are copied to the destination table. - -> [!NOTE] -> If is specified, any , , and -rows will also be copied to the server. No exception will be raised. - -While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. - -The collection maps from the columns to the destination database table. - - -## Examples -The following Console application demonstrates how to bulk load only the rows in a that match a specified state. In this case, only unchanged rows are added. The destination table is a table in the **AdventureWorks** database. - -In this example, a is created at run time and three rows are added to it. Before the method is executed, one of the rows is edited. -The method is called with a `DataRowState.Unchanged` `rowState` argument, so only the two unchanged rows are bulk copied to the destination. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.DataRowState#1](~/../sqlclient/doc/samples/SqlBulkCopy_DataRowState.cs#1)] -]]> - - - A - - did not specify a valid destination column name. - - - - An array of objects that will be copied to the destination table. - Copies all rows from the supplied array to a destination table specified by the property of the object. - - is busy serving it, and no other operations can be performed on the connection. - -The collection maps from the columns to the destination database table. - -## Examples -The following console application demonstrates how to bulk load data from a array. The destination table is a table in the **AdventureWorks** database. - -In this example, a is created at run time. A single row is selected from the to copy to the destination table. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.RowArray#1](~/../sqlclient/doc/samples/SqlBulkCopy_RowArray.cs#1)] - -]]> - - - A - - did not specify a valid destination column name. - - - - - An array of - - objects that will be copied to the destination table. - - - The asynchronous version of - , - which copies all rows from the supplied - - array to a destination table specified by the - - property of the - - object. - - - A task representing the asynchronous operation. - - - - - - Calling - - multiple times for the same instance before task completion. Calling - - and - - for the same instance before task completion. - - The connection drops or is closed during - - execution. - - Returned in the task object, the - - object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the - - object is closed before method execution. - - A - - did not specify a valid destination column name. - - - Returned in the task object, any error returned by SQL Server that occurred while opening the connection. - - - - - An array of - - objects that will be copied to the destination table. - - - The cancellation instruction. A - - value in this parameter makes this method equivalent to - . - - - The asynchronous version of - , - which copies all rows from the supplied - - array to a destination table specified by the - - property of the - - object. - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - - - - Calling - - multiple times for the same instance before task completion. - - Calling - - and - - for the same instance before task completion. - - The connection drops or is closed during - - execution. - - Returned in the task object, the - - object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the - - object is closed before method execution. - - A - - did not specify a valid destination column name. - - - Returned in the task object, any error returned by SQL Server that occurred while opening the connection. - - - - - A - - whose rows will be copied to the destination table. - - - The asynchronous version of - , - which copies all rows in the supplied - - to a destination table specified by the - - property of the - - object. - - - A task representing the asynchronous operation. - - - - - - Calling - - multiple times for the same instance before task completion. - - Calling - - and - - for the same instance before task completion. - - The connection drops or is closed during - - execution. - - Returned in the task object, the - - object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the - - object is closed before method execution. - - The - - was closed before the completed - - returned. - - The - 's associated connection was closed before the completed - - returned. - - A - - did not specify a valid destination column name. - - - Returned in the task object, any error returned by SQL Server that occurred while opening the connection. - - - - - A - - whose rows will be copied to the destination table. - - - The cancellation instruction. A - - value in this parameter makes this method equivalent to - . - - - The asynchronous version of - , - which copies all rows from the supplied - - array to a destination table specified by the - - property of the - - object. - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - To be added. - - - - - A - - whose rows will be copied to the destination table. - - - The asynchronous version of - , - which copies all rows in the supplied - - to a destination table specified by the - - property of the - - object. - - - A task representing the asynchronous operation. - - - - - - Calling - - multiple times for the same - instance before task completion. - - Calling - - and - - for the same instance before task completion. - - The connection drops or is closed during - - execution. - - Returned in the task object, the - - object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the - - object is closed before method execution. - - The - - was closed before the completed - - returned. - - The - 's associated connection was closed before the completed - - returned. - - A - - did not specify a valid destination column name. - - - Returned in the task object, any error returned by SQL Server that occurred while opening the connection. - - - - - A - - whose rows will be copied to the destination table. - - - The cancellation instruction. A - - value in this parameter makes this method equivalent to - . - - - The asynchronous version of - , - which copies all rows in the supplied - - to a destination table specified by the - - property of the - - object. - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - - - - Calling - - multiple times for the same instance before task completion. - - Calling - - and - - for the same instance before task completion. - - The connection drops or is closed during - - execution. - - Returned in the task object, the - - object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the - - object is closed before method execution. - - The - - was closed before the completed - - returned. - - The - 's associated connection was closed before the completed - - returned. - - A - - did not specify a valid destination column name. - - - Returned in the task object, any error returned by SQL Server that occurred while opening the connection. - - - - - A - - whose rows will be copied to the destination table. - - - The asynchronous version of - , - which copies all rows in the supplied - - to a destination table specified by the - - property of the - - object. - - - A task representing the asynchronous operation. - - - - - - Calling - - multiple times for the same instance before task completion. - - Calling - - and - - for the same instance before task completion. - - The connection drops or is closed during - - execution. - - Returned in the task object, the - - object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the - - object is closed before method execution. - - A - - did not specify a valid destination column name. - - - Returned in the task object, any error returned by SQL Server that occurred while opening the connection. - - - - - A - - whose rows will be copied to the destination table. - - - The cancellation instruction. A - - value in this parameter makes this method equivalent to - . - - - The asynchronous version of - , - which copies all rows in the supplied - - to a destination table specified by the - - property of the - - object. - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - - - - Calling - - multiple times for the same instance before task completion. - - Calling - - and - - for the same instance before task completion. - - The connection drops or is closed during - - execution. - - Returned in the task object, the - - object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the - - object is closed before method execution. - - A - - did not specify a valid destination column name. - - - Returned in the task object, any error returned by SQL Server that occurred while opening the connection. - - - - - A - - whose rows will be copied to the destination table. - - - A value from the - - enumeration. Only rows matching the row state are copied to the destination. - - - The asynchronous version of - , - which copies only rows that match the supplied row state in the supplied - to a destination table specified by the - property of the object. - - - A task representing the asynchronous operation. - - - - - - Calling - - multiple times for the same instance before task completion. - - Calling - - and - - for the same instance before task completion. - - The connection drops or is closed during - - execution. - - Returned in the task object, the - - object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the - - object is closed before method execution. - - A - - did not specify a valid destination column name. - - - Returned in the task object, any error returned by SQL Server that occurred while opening the connection. - - - - - A - - whose rows will be copied to the destination table. - - - A value from the - - enumeration. Only rows matching the row state are copied to the destination. - - - The cancellation instruction. A - - value in this parameter makes this method equivalent to - . - - - The asynchronous version of - , - which copies only rows that match the supplied row state in the supplied - - to a destination table specified by the - - property of the - - object. - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - - - - Calling - - multiple times for the same instance before task completion. - - Calling - - and - - for the same instance before task completion. - - The connection drops or is closed during - - execution. - - Returned in the task object, the - - object was closed during the method execution. - - Returned in the task object, there was a connection pool timeout. - - Returned in the task object, the - - object is closed before method execution. - - A - - did not specify a valid destination column name. - - - Returned in the task object, any error returned by SQL Server that occurred while opening the connection. - - - + + + Releases all resources used by the current instance of the class. + + + + Call Dispose when you are finished using the . The Dispose method leaves the in an unusable state. After calling Dispose, you must release all references to the so the garbage collector can reclaim the memory that the was occupying. + + + For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method. + + + Always call Dispose before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls the object's Finalize method. + + + + + + A whose rows will be copied to the destination table. + + + Copies all rows from the supplied array to a destination table specified by the property of the object. + + + A did not specify a valid destination column name. + + + + + A whose rows will be copied to the destination table. + + + Copies all rows in the supplied to a destination table specified by the property of the object. + + + + The copy operation starts at the next available row in the reader. Most of the time, the reader was just returned by or a similar call, so the next available row is the first row. To process multiple results, call on the data reader and call again. + + + Note that using modifies the state of the reader. The method will call until it returns false, the operation is aborted, or an error occurs. This means that the data reader will be in a different state, probably at the end of the result set, when the operation is complete. + + + While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. + + + The collection maps from the data reader columns to the destination database table. + + + + + The following console application demonstrates how to bulk load data from a . The destination table is a table in the AdventureWorks database. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.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(); + + // Set up the bulk copy object using a connection string. + // 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)) + { + 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;"; + } + } + + + + A did not specify a valid destination column name. + + + + + A whose rows will be copied to the destination table. + + + Copies all rows in the supplied to a destination table specified by the property of the object. + + + + All rows in the are copied to the destination table except those that have been deleted. + + + While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. + + + The collection maps from the columns to the destination database table. + + + + + The following Console application demonstrates how to bulk load data from a . The destination table is a table in the AdventureWorks database. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + In this example, a is created at run time and is the source of the SqlBulkCopy operation. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Perform an initial count on the destination table. + SqlCommand commandRowCount = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", + connection); + long countStart = System.Convert.ToInt32( + commandRowCount.ExecuteScalar()); + Console.WriteLine("Starting row count = {0}", countStart); + + // Create a table with some rows. + DataTable newProducts = MakeTable(); + + // Create the SqlBulkCopy object. + // Note that the column positions in the source DataTable + // match the column positions in the destination table so + // there is no need to map columns. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) + { + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"; + + try + { + // Write from the source to the destination. + bulkCopy.WriteToServer(newProducts); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + // 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 DataTable MakeTable() + { + // Create a new DataTable named NewProducts. + DataTable newProducts = new DataTable("NewProducts"); + + // Add three column objects to the table. + DataColumn productID = new DataColumn(); + productID.DataType = System.Type.GetType("System.Int32"); + productID.ColumnName = "ProductID"; + productID.AutoIncrement = true; + newProducts.Columns.Add(productID); + + DataColumn productName = new DataColumn(); + productName.DataType = System.Type.GetType("System.String"); + productName.ColumnName = "Name"; + newProducts.Columns.Add(productName); + + DataColumn productNumber = new DataColumn(); + productNumber.DataType = System.Type.GetType("System.String"); + productNumber.ColumnName = "ProductNumber"; + newProducts.Columns.Add(productNumber); + + // Create an array for DataColumn objects. + DataColumn[] keys = new DataColumn[1]; + keys[0] = productID; + newProducts.PrimaryKey = keys; + + // Add some new rows to the collection. + DataRow row = newProducts.NewRow(); + row["Name"] = "CC-101-WH"; + row["ProductNumber"] = "Cyclocomputer - White"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-BK"; + row["ProductNumber"] = "Cyclocomputer - Black"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-ST"; + row["ProductNumber"] = "Cyclocomputer - Stainless"; + newProducts.Rows.Add(row); + newProducts.AcceptChanges(); + + // Return the new DataTable. + return newProducts; + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + A did not specify a valid destination column name. + + + Performing Bulk Copy Operations + + + Overview of the SqlClient driver + + + + + A whose rows will be copied to the destination table. + + + A value from the enumeration. Only rows matching the row state are copied to the destination. + + + Copies only rows that match the supplied row state in the supplied to a destination table specified by the property of the object. + + + + Only rows in the that are in the states indicated in the argument and have not been deleted are copied to the destination table. + + + If is specified, any , , and rows will also be copied to the server. No exception will be raised. + + + While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. + + + The collection maps from the columns to the destination database table. + + + + + The following Console application demonstrates how to bulk load only the rows in a that match a specified state. In this case, only unchanged rows are added. The destination table is a table in the AdventureWorks database. + + + In this example, a is created at run time and three rows are added to it. Before the method is executed, one of the rows is edited. The method is called with a argument, so only the two unchanged rows are bulk copied to the destination. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Perform an initial count on the destination table. + SqlCommand commandRowCount = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", + connection); + long countStart = System.Convert.ToInt32( + commandRowCount.ExecuteScalar()); + Console.WriteLine("Starting row count = {0}", countStart); + + // Create a table with some rows. + DataTable newProducts = MakeTable(); + + // Make a change to one of the rows in the DataTable. + DataRow row = newProducts.Rows[0]; + row.BeginEdit(); + row["Name"] = "AAA"; + row.EndEdit(); + + // Create the SqlBulkCopy object. + // Note that the column positions in the source DataTable + // match the column positions in the destination table so + // there is no need to map columns. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) + { + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"; + + try + { + // Write unchanged rows from the source to the destination. + bulkCopy.WriteToServer(newProducts, DataRowState.Unchanged); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + // 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 DataTable MakeTable() + { + // Create a new DataTable named NewProducts. + DataTable newProducts = new DataTable("NewProducts"); + + // Add three column objects to the table. + DataColumn productID = new DataColumn(); + productID.DataType = System.Type.GetType("System.Int32"); + productID.ColumnName = "ProductID"; + productID.AutoIncrement = true; + newProducts.Columns.Add(productID); + + DataColumn productName = new DataColumn(); + productName.DataType = System.Type.GetType("System.String"); + productName.ColumnName = "Name"; + newProducts.Columns.Add(productName); + + DataColumn productNumber = new DataColumn(); + productNumber.DataType = System.Type.GetType("System.String"); + productNumber.ColumnName = "ProductNumber"; + newProducts.Columns.Add(productNumber); + + // Create an array for DataColumn objects. + DataColumn[] keys = new DataColumn[1]; + keys[0] = productID; + newProducts.PrimaryKey = keys; + + // Add some new rows to the collection. + DataRow row = newProducts.NewRow(); + row["Name"] = "CC-101-WH"; + row["ProductNumber"] = "Cyclocomputer - White"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-BK"; + row["ProductNumber"] = "Cyclocomputer - Black"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-ST"; + row["ProductNumber"] = "Cyclocomputer - Stainless"; + newProducts.Rows.Add(row); + newProducts.AcceptChanges(); + + // Return the new DataTable. + return newProducts; + } + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + A did not specify a valid destination column name. + + + + + An array of objects that will be copied to the destination table. + + + Copies all rows from the supplied array to a destination table specified by the property of the object. + + + + While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection. + + + The collection maps from the columns to the destination database table. + + + + + The following console application demonstrates how to bulk load data from a array. The destination table is a table in the AdventureWorks database. + + + In this example, a is created at run time. A single row is selected from the to copy to the destination table. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Perform an initial count on the destination table. + SqlCommand commandRowCount = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", + connection); + long countStart = System.Convert.ToInt32( + commandRowCount.ExecuteScalar()); + Console.WriteLine("Starting row count = {0}", countStart); + + // Create a table with some rows. + DataTable newProducts = MakeTable(); + + // Get a reference to a single row in the table. + DataRow[] rowArray = newProducts.Select("Name='CC-101-BK'"); + + // Create the SqlBulkCopy object. + // Note that the column positions in the source DataTable + // match the column positions in the destination table so + // there is no need to map columns. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) + { + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"; + + try + { + // Write the array of rows to the destination. + bulkCopy.WriteToServer(rowArray); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + // 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 DataTable MakeTable() + { + // Create a new DataTable named NewProducts. + DataTable newProducts = new DataTable("NewProducts"); + + // Add three column objects to the table. + DataColumn productID = new DataColumn(); + productID.DataType = System.Type.GetType("System.Int32"); + productID.ColumnName = "ProductID"; + productID.AutoIncrement = true; + newProducts.Columns.Add(productID); + + DataColumn productName = new DataColumn(); + productName.DataType = System.Type.GetType("System.String"); + productName.ColumnName = "Name"; + newProducts.Columns.Add(productName); + + DataColumn productNumber = new DataColumn(); + productNumber.DataType = System.Type.GetType("System.String"); + productNumber.ColumnName = "ProductNumber"; + newProducts.Columns.Add(productNumber); + + // Create an array for DataColumn objects. + DataColumn[] keys = new DataColumn[1]; + keys[0] = productID; + newProducts.PrimaryKey = keys; + + // Add some new rows to the collection. + DataRow row = newProducts.NewRow(); + row["Name"] = "CC-101-WH"; + row["ProductNumber"] = "Cyclocomputer - White"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-BK"; + row["ProductNumber"] = "Cyclocomputer - Black"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-ST"; + row["ProductNumber"] = "Cyclocomputer - Stainless"; + newProducts.Rows.Add(row); + newProducts.AcceptChanges(); + + // Return the new DataTable. + return newProducts; + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + A did not specify a valid destination column name. + + + + + An array of objects that will be copied to the destination table. + + + The asynchronous version of , + which copies all rows from the supplied array to a destination table specified by the property of the object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + Calling multiple times for the same instance before task completion. Calling and for the same instance before task completion. + The connection drops or is closed during execution. + Returned in the task object, the object was closed during the method execution. + Returned in the task object, there was a connection pool timeout. + Returned in the task object, the object is closed before method execution. + A did not specify a valid destination column name. + + + + Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + + + + + An array of objects that will be copied to the destination table. + + + The cancellation instruction. A value in this parameter makes this method equivalent to . + + + The asynchronous version of , + which copies all rows from the supplied array to a destination table specified by the property of the object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + Calling multiple times for the same instance before task completion. + Calling and for the same instance before task completion. + The connection drops or is closed during execution. + Returned in the task object, the object was closed during the method execution. + Returned in the task object, there was a connection pool timeout. + Returned in the task object, the object is closed before method execution. + A did not specify a valid destination column name. + + + + Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + + + + + A whose rows will be copied to the destination table. + + + The asynchronous version of , + which copies all rows in the supplied to a destination table specified by the property of the object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + Calling multiple times for the same instance before task completion. + Calling and for the same instance before task completion. + The connection drops or is closed during execution. + Returned in the task object, the object was closed during the method execution. + Returned in the task object, there was a connection pool timeout. + Returned in the task object, the object is closed before method execution. + The was closed before the completed returned. + The 's associated connection was closed before the completed returned. + A did not specify a valid destination column name. + + + + Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + + + + + A whose rows will be copied to the destination table. + + + The cancellation instruction. A value in this parameter makes this method equivalent to . + + + The asynchronous version of , + which copies all rows from the supplied array to a destination table specified by the property of the object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + + + A whose rows will be copied to the destination table. + + + The asynchronous version of , + which copies all rows in the supplied to a destination table specified by the property of the object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + Calling multiple times for the same instance before task completion. + Calling and for the same instance before task completion. + The connection drops or is closed during execution. + Returned in the task object, the object was closed during the method execution. + Returned in the task object, there was a connection pool timeout. + Returned in the task object, the object is closed before method execution. + The was closed before the completed returned. + The 's associated connection was closed before the completed returned. + A did not specify a valid destination column name. + + + + Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + + + + + A whose rows will be copied to the destination table. + + + The cancellation instruction. A value in this parameter makes this method equivalent to . + + + The asynchronous version of , + which copies all rows in the supplied to a destination table specified by the property of the object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + Calling multiple times for the same instance before task completion. + Calling and for the same instance before task completion. + The connection drops or is closed during execution. + Returned in the task object, the object was closed during the method execution. + Returned in the task object, there was a connection pool timeout. + Returned in the task object, the object is closed before method execution. + The was closed before the completed returned. + The 's associated connection was closed before the completed returned. + A did not specify a valid destination column name. + + + + Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + + + + + A whose rows will be copied to the destination table. + + + The asynchronous version of , + which copies all rows in the supplied to a destination table specified by the property of the object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + Calling multiple times for the same instance before task completion. + Calling and for the same instance before task completion. + The connection drops or is closed during execution. + Returned in the task object, the object was closed during the method execution. + Returned in the task object, there was a connection pool timeout. + Returned in the task object, the object is closed before method execution. + A did not specify a valid destination column name. + + + + Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + + + + + A whose rows will be copied to the destination table. + + + The cancellation instruction. A value in this parameter makes this method equivalent to . + + + The asynchronous version of , + which copies all rows in the supplied to a destination table specified by the property of the object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + Calling multiple times for the same instance before task completion. + Calling and for the same instance before task completion. + The connection drops or is closed during execution. + Returned in the task object, the object was closed during the method execution. + Returned in the task object, there was a connection pool timeout. + Returned in the task object, the object is closed before method execution. + A did not specify a valid destination column name. + + + + Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + + + + + A whose rows will be copied to the destination table. + + + A value from the enumeration. Only rows matching the row state are copied to the destination. + + + The asynchronous version of , + which copies only rows that match the supplied row state in the supplied to a destination table specified by the property of the object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + Calling multiple times for the same instance before task completion. + Calling and for the same instance before task completion. + The connection drops or is closed during execution. + Returned in the task object, the object was closed during the method execution. + Returned in the task object, there was a connection pool timeout. + Returned in the task object, the object is closed before method execution. + A did not specify a valid destination column name. + + + + Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + + + + + A whose rows will be copied to the destination table. + + + A value from the enumeration. Only rows matching the row state are copied to the destination. + + + The cancellation instruction. A value in this parameter makes this method equivalent to . + + + The asynchronous version of , + which copies only rows that match the supplied row state in the supplied to a destination table specified by the property of the object. + The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + Calling multiple times for the same instance before task completion. + Calling and for the same instance before task completion. + The connection drops or is closed during execution. + Returned in the task object, the object was closed during the method execution. + Returned in the task object, there was a connection pool timeout. + Returned in the task object, the object is closed before method execution. + A did not specify a valid destination column name. + + + + Returned in the task object, any error returned by SQL Server that occurred while opening the connection. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnMapping.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnMapping.xml index f8d258ff32..f49680d489 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnMapping.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnMapping.xml @@ -1,294 +1,1142 @@ - - - - - Defines the mapping between a column in a - - instance's data source and a column in the instance's destination table. - - - collection is empty - the columns are mapped implicitly based on ordinal position. -For this to work, source and target schemas must match. If they do not, an will be thrown. - -If the collection is not empty, not every column present in the data source has to be specified. Those not mapped by the collection -are ignored. - -You can refer to source and target columns by either name or ordinal. You can also mix by-name and by-ordinal column references in the same mappings collection. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the -destination matches the number of columns in the source, and each destination column is in the same ordinal position as its corresponding source column, the column names do not match. - objects are used to create a column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMapping#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMapping.cs#1)] -]]> - - - - - Parameterless constructor that initializes a new - - object. - - - -property or the property, and define the destination for the mapping using the - property or the property. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. - objects are used to create a column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMapping#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMapping.cs#1)] -]]> - - - - - The ordinal position of the source column within the data source. - - - The ordinal position of the destination column within the destination table. - - - Creates a new column mapping, using column ordinals to refer to source and destination columns. - - - objects are used to create a column map for the bulk copy based on the ordinal positions of the columns. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier -and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs#1)] -]]> - - - - - The ordinal position of the source column within the data source. - - - The name of the destination column within the destination table. - - - Creates a new column mapping, using a column ordinal to refer to the source column and a column name for the target column. - - - objects are used to create a -column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and -faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingOrdinalName#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs#1)] -]]> - - - - - The name of the source column within the data source. - - - The ordinal position of the destination column within the destination table. - - - Creates a new column mapping, using a column name to refer to the source column and a column ordinal for the target column. - - - objects are used to create -a column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is -provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to -use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingNameOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs#1)] -]]> - - - - - The name of the source column within the data source. - - - The name of the destination column within the destination table. - - - Creates a new column mapping, using column names to refer to source and destination columns. - - - objects are used to create a -column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMapping#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMapping.cs#1)] -]]> - - - - - Name of the column being mapped in the destination database table. - - - The string value of the - - property. - - - and properties are mutually exclusive. -The last value set takes precedence. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. - objects are used to create a column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingDestinationColumn#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs#1)] -]]> - - - - - Ordinal value of the destination column within the destination table. - - - The integer value of the - - property, or -1 if the property has not been set. - - - and properties are mutually exclusive. -The last value set takes precedence. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the -destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a -column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingDestinationOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs#1)] -]]> - - - - - Name of the column being mapped in the data source. - - - The string value of the - - property. - - - and properties are mutually exclusive. -The last value set takes precedence. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the -destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a -column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingDestinationColumn#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs#1)] -]]> - - - - - The ordinal position of the source column within the data source. - - - The integer value of the - - property. - - - and properties are mutually exclusive. -The last value set takes precedence. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the destination -matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the -bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingDestinationOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs#1)] -]]> - - - + + + + + Defines the mapping between a column in a instance's data source and a column in the instance's destination table. + + + + Column mappings define the mapping between data source and the target table. + + + If mappings are not defined - that is, the collection is empty - the columns are mapped implicitly based on ordinal position. For this to work, source and target schemas must match. If they do not, an will be thrown. + + + If the collection is not empty, not every column present in the data source has to be specified. Those not mapped by the collection are ignored. + + + You can refer to source and target columns by either name or ordinal. You can also mix by-name and by-ordinal column references in the same mappings collection. + + + + + The following example bulk copies data from a source table in the AdventureWorks + sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, and each destination column is in the same ordinal position as its corresponding source column, the column names do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for usingSqlBulkCopyonly. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + Parameterless constructor that initializes a new object. + + + If you use this constructor, you must then define the source for the mapping using the property or the property, and define the destination for the mapping using the property or the property. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + The ordinal position of the source column within the data source. + + + The ordinal position of the destination column within the destination table. + + + Creates a new column mapping, using column ordinals to refer to source and destination columns. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy based on the ordinal positions of the columns. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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 ordinal. + SqlBulkCopyColumnMapping columnMapID = + new SqlBulkCopyColumnMapping(0, 0); + bulkCopy.ColumnMappings.Add(columnMapID); + + SqlBulkCopyColumnMapping columnMapName = + new SqlBulkCopyColumnMapping(1, 2); + bulkCopy.ColumnMappings.Add(columnMapName); + + SqlBulkCopyColumnMapping columnMapNumber = + new SqlBulkCopyColumnMapping(2, 1); + bulkCopy.ColumnMappings.Add(columnMapNumber); + + // 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;"; + } + } + + + + + + The ordinal position of the source column within the data source. + + + The name of the destination column within the destination table. + + + Creates a new column mapping, using a column ordinal to refer to the source column and a column name for the target column. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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 ordinal and name. + SqlBulkCopyColumnMapping columnMapID = + new SqlBulkCopyColumnMapping(0, "ProdID"); + bulkCopy.ColumnMappings.Add(columnMapID); + + SqlBulkCopyColumnMapping columnMapName = + new SqlBulkCopyColumnMapping(1, "ProdName"); + bulkCopy.ColumnMappings.Add(columnMapName); + + SqlBulkCopyColumnMapping columnMapNumber = + new SqlBulkCopyColumnMapping(2, "ProdNum"); + bulkCopy.ColumnMappings.Add(columnMapNumber); + + // 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;"; + } + } + + + + + + The name of the source column within the data source. + + + The ordinal position of the destination column within the destination table. + + + Creates a new column mapping, using a column name to refer to the source column and a column ordinal for the target column. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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 and ordinal. + SqlBulkCopyColumnMapping columnMapID = + new SqlBulkCopyColumnMapping("ProductID", 0); + bulkCopy.ColumnMappings.Add(columnMapID); + + SqlBulkCopyColumnMapping columnMapName = + new SqlBulkCopyColumnMapping("Name", 2); + bulkCopy.ColumnMappings.Add(columnMapName); + + SqlBulkCopyColumnMapping columnMapNumber = + new SqlBulkCopyColumnMapping("ProductNumber", 1); + bulkCopy.ColumnMappings.Add(columnMapNumber); + + // 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;"; + } + } + + + + + + The name of the source column within the data source. + + + The name of the destination column within the destination table. + + + Creates a new column mapping, using column names to refer to source and destination columns. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + Name of the column being mapped in the destination database table. + + + The string value of the property. + + + The and properties are mutually exclusive. The last value set takes precedence. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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 source and destination. + SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(); + mapID.SourceColumn = "ProductID"; + mapID.DestinationColumn = "ProdID"; + bulkCopy.ColumnMappings.Add(mapID); + + SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping(); + mapName.SourceColumn = "Name"; + mapName.DestinationColumn = "ProdName"; + bulkCopy.ColumnMappings.Add(mapName); + + SqlBulkCopyColumnMapping mapNumber = new SqlBulkCopyColumnMapping(); + mapNumber.SourceColumn = "ProductNumber"; + mapNumber.DestinationColumn = "ProdNum"; + bulkCopy.ColumnMappings.Add(mapNumber); + + // 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;"; + } + } + + + + + + Ordinal value of the destination column within the destination table. + + + The integer value of the property, or -1 if the property has not been set. + + + The and properties are mutually exclusive. The last value set takes precedence. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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 source and destination. + SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(); + mapID.SourceOrdinal = 0; + mapID.DestinationOrdinal = 0; + bulkCopy.ColumnMappings.Add(mapID); + + SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping(); + mapName.SourceOrdinal = 1; + mapName.DestinationOrdinal = 2; + bulkCopy.ColumnMappings.Add(mapName); + + SqlBulkCopyColumnMapping mapNumber = new SqlBulkCopyColumnMapping(); + mapNumber.SourceOrdinal = 2; + mapNumber.DestinationOrdinal = 1; + bulkCopy.ColumnMappings.Add(mapNumber); + + // 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;"; + } + } + + + + + + Name of the column being mapped in the data source. + + + The string value of the property. + + + The and properties are mutually exclusive. The last value set takes precedence. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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 source and destination. + SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(); + mapID.SourceColumn = "ProductID"; + mapID.DestinationColumn = "ProdID"; + bulkCopy.ColumnMappings.Add(mapID); + + SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping(); + mapName.SourceColumn = "Name"; + mapName.DestinationColumn = "ProdName"; + bulkCopy.ColumnMappings.Add(mapName); + + SqlBulkCopyColumnMapping mapNumber = new SqlBulkCopyColumnMapping(); + mapNumber.SourceColumn = "ProductNumber"; + mapNumber.DestinationColumn = "ProdNum"; + bulkCopy.ColumnMappings.Add(mapNumber); + + // 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;"; + } + } + + + + + + The ordinal position of the source column within the data source. + + + The integer value of the property. + + + The and properties are mutually exclusive. The last value set takes precedence. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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 source and destination. + SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(); + mapID.SourceOrdinal = 0; + mapID.DestinationOrdinal = 0; + bulkCopy.ColumnMappings.Add(mapID); + + SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping(); + mapName.SourceOrdinal = 1; + mapName.DestinationOrdinal = 2; + bulkCopy.ColumnMappings.Add(mapName); + + SqlBulkCopyColumnMapping mapNumber = new SqlBulkCopyColumnMapping(); + mapNumber.SourceOrdinal = 2; + mapNumber.DestinationOrdinal = 1; + bulkCopy.ColumnMappings.Add(mapNumber); + + // 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;"; + } + } + + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnMappingCollection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnMappingCollection.xml index 5c8ddd2ef3..8ba86611b0 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnMappingCollection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnMappingCollection.xml @@ -1,298 +1,1319 @@ - - - - Collection of objects that inherits from . - - collection is empty - the columns are mapped implicitly based on ordinal position. -For this to work, source and target schemas must match. If they do not, an is thrown. - -If the collection is not empty, not every column present in the data source has to be specified. Those not mapped by the collection are -ignored. - -You can refer to source and target columns by either name or ordinal. You can mix by-name and by-ordinal column references in the same mappings collection. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. - are added to the for the - object to create a column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to -use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingCollection#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs#1)] - -]]> - - - - The object that describes the mapping to be added to the collection. - Adds the specified mapping to the . - A object. - - objects are used to create a column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMapping#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMapping.cs)] - -]]> - - - - - The ordinal position of the source column within the data source. - The ordinal position of the destination column within the destination table. - Creates a new and adds it to the collection, using ordinals to specify both source and destination columns. - A column mapping. - - is thrown. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. - objects are used to create a column map for the bulk copy using the ordinal position of the source and destination columns. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingCollectionOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs#1)] - -]]> - - - - The ordinal position of the source column within the data source. - The name of the destination column within the destination table. - Creates a new and adds it to the collection, using an ordinal for the source column and a string for the destination column. - A column mapping. - - is thrown. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the -destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a -column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy_ColumnMappingIndexColName#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs#1)] - -]]> - - - - The name of the source column within the data source. - The ordinal position of the destination column within the destination table. - Creates a new and adds it to the collection, using a column name to describe the source column and an ordinal to specify the destination column. - A column mapping. - - is thrown. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. - objects are used to create a column map for the bulk copy. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingColNameIndex#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs#1)] - -]]> - - - - The name of the source column within the data source. - The name of the destination column within the destination table. - Creates a new and adds it to the collection, using column names to specify both source and destination columns. - A column mapping. - - is thrown. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. The code creates a - object by specifying the column names. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingCollection#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs#1)] - -]]> - - - - Clears the contents of the collection. - - method is most commonly used when you use a single -instance to process more than one bulk copy operation. If you create column mappings for one bulk copy operation, you must clear the - after the method and before processing the next bulk copy. - -Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate - for each operation. - -## Examples -The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. -Although not strictly necessary in this example (because the ordinal positions of the source and destination columns do match), the example defines column mappings for each bulk copy operation. -The method must be used after the first bulk copy is performed and before the next bulk copy's column mappings are defined. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingOrdersDetails#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs#1)] - -]]> - - - - A valid object. - Gets a value indicating whether a specified object exists in the collection. - - if the specified mapping exists in the collection; otherwise . - - - The one-dimensional array that is the destination of the elements copied from - . The array must have zero-based indexing. - The zero-based index in at which copying begins. - Copies the elements of the to an array of - items, starting at a particular index. - - - - The object for which to search. - Gets the index of the specified object. - The zero-based index of the column mapping, or -1 if the column mapping is not found in the collection. - To be added. - - - Integer value of the location within the at which to insert the new - . - - object to be inserted in the collection. - Insert a new at the index specified. - To be added. - - - The zero-based index of the to find. - Gets the object at the specified index. - A object. - To be added. - - - - object to be removed from the collection. - Removes the specified element from the . - - method is most commonly used when you use a single -instance to process more than one bulk copy operation. If you create column mappings for one bulk copy operation, you must remove mappings that no longer apply after the - method is called and before defining mapping for the next bulk copy. You can clear the entire collection by using the - method, or remove mappings individually using the -method or the method. - -Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate - for each operation. - -## Examples -The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. -Although not strictly necessary in this example (because the ordinal positions of the source and destination columns do match), the example defines column mappings for each bulk copy operation. -Both bulk copies include a mapping for the **SalesOrderID**, so rather than clearing the entire collection between bulk copy operations, the example removes all mappings except for the **SalesOrderID** -mapping and then adds the appropriate mappings for the second bulk copy operation. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingRemove#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingRemove.cs#1)] - -]]> - - - - The zero-based index of the object to be removed from the collection. - Removes the mapping at the specified index from the collection. - - method is most commonly used when you use a single -instance to process more than one bulk copy operation. If you create column mappings for one bulk copy operation, you must remove mappings that no longer apply after the - method is called and before defining mapping for the next bulk copy. You can clear the entire collection by using the - method, or remove mappings individually using the -method or the method. - -Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate - for each operation. - -## Examples -The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. -Although not strictly necessary in this example (because the ordinal positions of the source and destination columns do match), the example defines column mappings for each bulk copy operation. -Both bulk copies include a mapping for the **SalesOrderID**, so rather than clearing the entire collection between bulk copy operations, the example removes all mappings except for the -**SalesOrderID** mapping and then adds the appropriate mappings for the second bulk copy operation. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnMappingRemoveAt#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs#1)] - -]]> - - - - Gets a value indicating whether access to the is synchronized (thread safe). - `true` if access to the is synchronized (thread safe); otherwise, `false`. - - + + + + + Collection of objects that inherits from . + + + + Column mappings define the mapping between data source and the target table. + + + If mappings are not defined - that is, the collection is empty - the columns are mapped implicitly based on ordinal position. For this to work, source and target schemas must match. If they do not, an is thrown. + + + If the collection is not empty, not every column present in the data source has to be specified. Those not mapped by the collection are ignored. + + + You can refer to source and target columns by either name or ordinal. You can mix by-name and by-ordinal column references in the same mappings collection. + + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. are added to the for the object to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + The object that describes the mapping to be added to the collection. + + + Adds the specified mapping to the . + + + A object. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + The ordinal position of the source column within the data source. + + + The ordinal position of the destination column within the destination table. + + + Creates a new and adds it to the collection, using ordinals to specify both source and destination columns. + + + A column mapping. + + + Mappings in a collection must be uniform: either all integer/integer pairs, all string/string pairs, all integer/string pairs, or all string/integer pairs. If you try to add a mapping that is different from others already in the collection, an is thrown. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy using the ordinal position of the source and destination columns. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + The ordinal position of the source column within the data source. + + + The name of the destination column within the destination table. + + + Creates a new and adds it to the collection, using an ordinal for the source column and a string for the destination column. + + + A column mapping. + + + Mappings in a collection must be uniform: either all integer/integer pairs, all string/string pairs, all integer/string pairs, or all string/integer pairs. If you try to add a mapping that is different from others already in the collection, an is thrown. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + The name of the source column within the data source. + + + The ordinal position of the destination column within the destination table. + + + Creates a new and adds it to the collection, using a column name to describe the source column and an ordinal to specify the destination column. + + + A column mapping. + + + Mappings in a collection must be uniform: either all integer/integer pairs, all string/string pairs, all integer/string pairs, or all string/integer pairs. If you try to add a mapping that is different from others already in the collection, an is thrown. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the bulk copy. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + The name of the source column within the data source. + + + The name of the destination column within the destination table. + + + Creates a new and adds it to the collection, using column names to specify both source and destination columns. + + + A column mapping. + + + Mappings in a collection must be uniform: either all integer/integer pairs, all string/string pairs, all integer/string pairs, or all string/integer pairs. If you try to add a mapping that is different from others already in the collection, an is thrown. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. The code creates a object by specifying the column names. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + Clears the contents of the collection. + + + + The method is most commonly used when you use a single instance to process more than one bulk copy operation. If you create column mappings for one bulk copy operation, you must clear the after the method and before processing the next bulk copy. + + + Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate for each operation. + + + + + The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. Although not strictly necessary in this example (because the ordinal positions of the source and destination columns do match), the example defines column mappings for each bulk copy operation. The method must be used after the first bulk copy is performed and before the next bulk copy's column mappings are defined. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + + + A valid object. + + + Gets a value indicating whether a specified object exists in the collection. + + if the specified mapping exists in the collection; otherwise . + + + + The one-dimensional array that is the destination of the elements copied from . The array must have zero-based indexing. + + + The zero-based index in at which copying begins. + + + Copies the elements of the to an array of items, starting at a particular index. + + + + + The object for which to search. + + + Gets the index of the specified object. + + + The zero-based index of the column mapping, or -1 if the column mapping is not found in the collection. + + + + + Integer value of the location within the at which to insert the new . + + object to be inserted in the collection. + + Insert a new at the index specified. + + + + + The zero-based index of the to find. + + + Gets the object at the specified index. + + + A object. + + + + object to be removed from the collection. + + Removes the specified element from the . + + + + The method is most commonly used when you use a single instance to process more than one bulk copy operation. If you create column mappings for one bulk copy operation, you must remove mappings that no longer apply after the method is called and before defining mapping for the next bulk copy. You can clear the entire collection by using the method, or remove mappings individually using the method or the method. + + + Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate for each operation. + + + + + The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. Although not strictly necessary in this example (because the ordinal positions of the source and destination columns do match), the example defines column mappings for each bulk copy operation. Both bulk copies include a mapping for the SalesOrderID, so rather than clearing the entire collection between bulk copy operations, the example removes all mappings except for the SalesOrderID mapping and then adds the appropriate mappings for the second bulk copy operation. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + + + The zero-based index of the object to be removed from the collection. + + + Removes the mapping at the specified index from the collection. + + + + The method is most commonly used when you use a single instance to process more than one bulk copy operation. If you create column mappings for one bulk copy operation, you must remove mappings that no longer apply after the method is called and before defining mapping for the next bulk copy. You can clear the entire collection by using the method, or remove mappings individually using the method or the method. + + + Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate for each operation. + + + + + The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. Although not strictly necessary in this example (because the ordinal positions of the source and destination columns do match), the example defines column mappings for each bulk copy operation. Both bulk copies include a mapping for the SalesOrderID, so rather than clearing the entire collection between bulk copy operations, the example removes all mappings except for the SalesOrderID mapping and then adds the appropriate mappings for the second bulk copy operation. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Rather than clearing mappings that are not necessary + // for the next bulk copyo peration, the unneeded mappings + // are removed with the RemoveAt method. + bulkCopy.ColumnMappings.RemoveAt(2); + bulkCopy.ColumnMappings.RemoveAt(1); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + bulkCopy.WriteToServer(readerDetail); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + + + Gets a value indicating whether access to the is synchronized (thread safe). + + + if access to the is synchronized (thread safe); otherwise, . + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHint.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHint.xml index d3e846546c..3b205e171d 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHint.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHint.xml @@ -1,131 +1,447 @@ - - - - - Defines the sort order for a column in a - - instance's destination table, according to the clustered index on the table. - - - collection is not empty, order hints can only be provided for valid -destination columns which have been mapped. - -If a of Unspecified is given, an will be thrown. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHint#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHint.cs#1)] -]]> - - - - - - The name of the destination column within the destination table. - - - The sort order of the corresponding destination column. - - - Creates a new column order hint for the specified destination column. - - - [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHint#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHint.cs#1)] -]]> - - - - - - Name of the destination column in the destination table for which the hint is being provided. - - - The string value of the - - property. - - - will be thrown if a null or empty string is given. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHintColumn#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs#1)] -]]> - - The value is null or empty. - - - - - The sort order of the destination column in the destination table. - - - The SortOrder value of the - - property. - - - will be thrown if a of Unspecified is given. - -## Examples -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHintSortOrder#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs#1)] -]]> - - The sort order cannot be unspecified for a column order hint. - - + + + + + Defines the sort order for a column in a instance's destination table, according to the clustered index on the table. + + + + Column order hints define the sort order of the column in the destination table. + + + SqlBulkCopy's performance is improved if the data being imported is sorted according to the clustered index on the table, if any. If the data is sorted in an order that differs from the order of a clustered index key or if there is no clustered index on the table, the order hint is ignored. + + + Order hints can be specified for any number of columns in the destination table. By default, the bulk insert operation assumes the data is unordered if no hints are provided. + + + The column names supplied must be valid column names in the destination table. The order in which hints can be specified is arbitrary. A single column name cannot be specified more than once. + + + If the collection is not empty, order hints can only be provided for valid destination columns which have been mapped. + + + If a of Unspecified is given, an will be thrown. + + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Setup an order hint for the ProductNumber column. + SqlBulkCopyColumnOrderHint hintNumber = + new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); + bulkCopy.ColumnOrderHints.Add(hintNumber); + + // 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;"; + } + } + + + + + + The name of the destination column within the destination table. + + + The sort order of the corresponding destination column. + + + Creates a new column order hint for the specified destination column. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Setup an order hint for the ProductNumber column. + SqlBulkCopyColumnOrderHint hintNumber = + new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); + bulkCopy.ColumnOrderHints.Add(hintNumber); + + // 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;"; + } + } + + + + + + Name of the destination column in the destination table for which the hint is being provided. + + + The string value of the property. + + + An will be thrown if a null or empty string is given. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Setup an order hint for the ProductNumber column. + SqlBulkCopyColumnOrderHint hintNumber = + new SqlBulkCopyColumnOrderHint("number", SortOrder.Ascending); + hintNumber.Column = "ProductNumber"; + bulkCopy.ColumnOrderHints.Add(hintNumber); + + // 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;"; + } + } + + + + The value is null or empty. + + + + + The sort order of the destination column in the destination table. + + + The SortOrder value of the property. + + + An will be thrown if a of Unspecified is given. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Setup an order hint for the ProductNumber column. + SqlBulkCopyColumnOrderHint hintNumber = + new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); + hintNumber.SortOrder = SortOrder.Descending; + bulkCopy.ColumnOrderHints.Add(hintNumber); + + // 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;"; + } + } + + + + The sort order cannot be unspecified for a column order hint. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHintCollection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHintCollection.xml index 1f6912efa5..528a6a6065 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHintCollection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHintCollection.xml @@ -1,226 +1,1028 @@ - - - - Collection of objects that inherits from . - - + + + + Collection of objects that inherits from . + + + + Column order hints define the sort order of the column in the destination table. + + + SqlBulkCopy's performance is improved if the data being imported is sorted according to the clustered index on the table, if any. If the data is sorted in an order that differs from the order of a clustered index key or if there is no clustered index on the table, the order hint is ignored. + + + Order hints can be specified for any number of columns in the destination table. By default, the bulk insert operation assumes the data is unordered if no hints are provided. + + + The column names supplied must be valid column names in the destination table. The order in which hints can be specified is arbitrary. A single column name cannot be specified more than once. + + + If the collection is not empty, order hints can only be provided for valid destination columns which have been mapped. + + + If a of Unspecified is given, an will be thrown. + + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. s are added to the of the object to specify order hints for the bulk copy operation. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Specify the sort order for the ProductNumber column in + // the destination table. + bulkCopy.ColumnOrderHints.Add("ProductNumber", SortOrder.Ascending); + + // 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;"; + } + } + + + + + + The object that describes the order hint to be added to the collection. + + + Adds the specified order hint to the . + + + A object. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Specify the sort order for the ProductNumber column in + // the destination table. + // Setup an order hint for the ProductNumber column. + SqlBulkCopyColumnOrderHint hintNumber = + new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); + bulkCopy.ColumnOrderHints.Add(hintNumber); + + // 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;"; + } + } + + + + The value is null. + + + + + The name of the destination column within the destination table. + + + The sort order of the corresponding destination column. + + + Creates a new and adds it to the collection. + + + A column column order hint. + + + + The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. A SqlBulkCopyColumnOrderHint object is added to the by providing the destination column name and its sort order. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Specify the sort order for the ProductNumber column in + // the destination table. + bulkCopy.ColumnOrderHints.Add("ProductNumber", SortOrder.Ascending); + + // 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;"; + } + } + + + + + + Clears the contents of the collection. + + + + The method is most commonly used when you use a single instance to process more than one bulk copy operation. If you create column order hints for one bulk copy operation, you must clear the after the method and before processing the next bulk copy. + + + Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate for each operation. + + + + + The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. The example defines a column order hint for each bulk copy operation. The method must be used after the first bulk copy is performed and before the next bulk copy's order hint is defined. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Add order hint for OrderDate column. + bulkCopy.ColumnOrderHints.Add("OrderDate", SortOrder.Ascending); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Clear the ColumnOrderHintCollection. + bulkCopy.ColumnOrderHints.Clear(); + + // Add order hint for SalesOrderID column. + bulkCopy.ColumnOrderHints.Add("SalesOrderID", SortOrder.Ascending); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + + + A valid object. + + + Gets a value indicating whether a specified object exists in the collection. + + + if the specified column order hint exists in the collection; otherwise . + + + + + The one-dimensional array that is the destination of the elements copied from . The array must have zero-based indexing. + + + The zero-based index in at which copying begins. + + + Copies the elements of the to an array of items, starting at a particular index. + + + + + The object for which to search. + + + Gets the index of the specified object. + + + The zero-based index of the column order hint, or -1 if the column order hint is not found in the collection. + + + + + Integer value of the location within the at which to insert the new . + + + object to be inserted in the collection. + + + Insert a new at the index specified. + + + The order in which column order hints can be added is arbitrary. + + + The index is less than zero or greater than the size of the collection. + + + A null column order hint cannot be added to the collection. + + + + + The zero-based index of the to find. + + + Gets the object at the specified index. + + + A object. + + + The index must be non-negative and less than the size of the collection. + + + + object to be removed from the collection. + + Removes the specified element from the . + + + + The Remove method is most commonly used when you use a single instance to process more than one bulk copy operation. If you create column order hints for one bulk copy operation, you must clear the after the method and before processing the next bulk copy. + + + You can clear the entire collection by using the method, or remove hints individually using the Remove method or the method. + + + Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate for each operation. + + + + + The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. The example defines a column order hint for the OrderDate column in the first bulk copy operation. The hint is removed before the second bulk copy operation. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); -## Remarks -Column order hints define the sort order of the column in the destination table. - -SqlBulkCopy's performance is improved if the data being imported is sorted according to the clustered index on the table, if any. -If the data is sorted in an order that differs from the order of a clustered index key or if there is no clustered index on the table, the order hint is ignored. - -Order hints can be specified for any number of columns in the destination table. By default, the bulk insert operation assumes the data is -unordered if no hints are provided. - -The column names supplied must be valid column names in the destination table. The order in which hints can be specified is arbitrary. -A single column name cannot be specified more than once. - -If the collection is not empty, order hints can only be provided for valid -destination columns which have been mapped. - -If a of Unspecified is given, an will be thrown. - -## Examples - -The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. -s are added to the of the - object to specify order hints for the bulk copy operation. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to -use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHintCollection#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs#1)] - -]]> - - - - - The object that describes the order hint to be added to the collection. - Adds the specified order hint to the . - A object. - - [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionAdd#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs)] - -]]> - - - The value is null. - - - - The name of the destination column within the destination table. - The sort order of the corresponding destination column. - Creates a new and adds it to the collection. - A column column order hint. - - by providing the destination column name and its sort order. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionAdd2#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs#1)] - -]]> - - - - - Clears the contents of the collection. - - method is most commonly used when you use a single -instance to process more than one bulk copy operation. If you create column order hints for one bulk copy operation, you must clear the - after the method and before processing the next bulk copy. - -Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate - for each operation. - -## Examples -The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. -The example defines a column order hint for each bulk copy operation. -The method must be used after the first bulk copy is performed and before the next bulk copy's order hint is defined. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionClear#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs#1)] - -]]> - - - - A valid object. - Gets a value indicating whether a specified object exists in the collection. - - if the specified column order hint exists in the collection; otherwise . - - - The one-dimensional array that is the destination of the elements copied from - . The array must have zero-based indexing. - The zero-based index in at which copying begins. - Copies the elements of the to an array of - items, starting at a particular index. - - - - The object for which to search. - Gets the index of the specified object. - The zero-based index of the column order hint, or -1 if the column order hint is not found in the collection. - To be added. - - - Integer value of the location within the at which to insert the new - . - - object to be inserted in the collection. - Insert a new at the index specified. - The order in which column order hints can be added is arbitrary. - The index is less than zero or greater than the size of the collection. - A null column order hint cannot be added to the collection. - - - The zero-based index of the to find. - Gets the object at the specified index. - A object. - To be added. - The index must be non-negative and less than the size of the collection. - - - - object to be removed from the collection. - Removes the specified element from the . - - -instance to process more than one bulk copy operation. If you create column order hints for one bulk copy operation, you must clear the - after the method and before processing the next bulk copy. - -You can clear the entire collection by using the - method, or remove hints individually using the Remove method or the method. - -Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate - for each operation. - -## Examples -The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. -The example defines a column order hint for the **OrderDate** column in the first bulk copy operation. The hint is removed before the second bulk copy operation. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionRemove#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs#1)] - -]]> - - The value is null. - - - The zero-based index of the object to be removed from the collection. - Removes the column order hint at the specified index from the collection. - - method is most commonly used when you use a single -instance to process more than one bulk copy operation. If you create column order hints for one bulk copy operation, you must clear the - after the method and before processing the next bulk copy. -You can clear the entire collection by using the - method, or remove hints individually using the -method or the method. - -Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate - for each operation. - -## Examples -The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. -The example defines a column order hint for the **OrderDate** column in the first bulk copy operation. The hint is removed before the second bulk copy operation. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a -Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionRemoveAt#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs#1)] - -]]> - - The index must be non-negative and less than the size of the collection. - - - Gets a value indicating whether access to the is synchronized (thread safe). - `true` if access to the is synchronized (thread safe); otherwise, `false`. - - + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Add the order hint for the OrderDate column. + SqlBulkCopyColumnOrderHint hintDate = + new SqlBulkCopyColumnOrderHint("OrderDate", SortOrder.Ascending); + bulkCopy.ColumnOrderHints.Add(hintDate); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Remove the order hint for the OrderDate column. + bulkCopy.ColumnOrderHints.Remove(hintDate); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + The value is null. + + + + + The zero-based index of the object to be removed from the collection. + + + Removes the column order hint at the specified index from the collection. + + + + The method is most commonly used when you use a single instance to process more than one bulk copy operation. If you create column order hints for one bulk copy operation, you must clear the after the method and before processing the next bulk copy. You can clear the entire collection by using the method, or remove hints individually using the method or the method. + + + Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate for each operation. + + + + + The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details. The example defines a column order hint for the OrderDate column in the first bulk copy operation. The hint is removed before the second bulk copy operation. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Add the order hint for the OrderDate column. + SqlBulkCopyColumnOrderHint hintDate = + new SqlBulkCopyColumnOrderHint("OrderDate", SortOrder.Ascending); + bulkCopy.ColumnOrderHints.Add(hintDate); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Remove the order hint for the OrderDate column. + bulkCopy.ColumnOrderHints.RemoveAt(0); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } + } + + + + The index must be non-negative and less than the size of the collection. + + + + + Gets a value indicating whether access to the is synchronized (thread safe). + + + if access to the is synchronized (thread safe); otherwise, . + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyOptions.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyOptions.xml index 152fcbde42..50f149ee01 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyOptions.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyOptions.xml @@ -1,67 +1,154 @@ - - - - Bitwise flag that specifies one or more options to use with an instance of . - - enumeration when you construct a instance to change how the - methods for that instance behave. - -## Examples -The following console application demonstrates how to perform a bulk load that copies the value in the identity column of the source table to the corresponding column in the destination table, -instead of generating a new value for each row's identity column. - -To see how the option changes the way the bulk load works, run the sample with the **dbo.BulkCopyDemoMatchingColumns** table empty. All rows load from the source. -Next, run the sample again without emptying the table. An exception is thrown, and the code writes a message to the console window notifying you that rows were not added because of -primary key violations. - -> [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). -This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, -it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -[!code-csharp[SqlBulkCopy.KeepIdentity#1](~/../sqlclient/doc/samples/SqlBulkCopy_KeepIdentity.cs)] - -]]> - - - - - - - - - Check constraints while data is being inserted. By default, constraints are not checked. - - - Use the default values for all options. - - - When specified, cause the server to fire the insert triggers for the rows being inserted into the database. - - - Preserve source identity values. When not specified, identity values are assigned by the destination. - - - Preserve null values in the destination table regardless of the settings for default values. When not specified, null values are replaced by default values where applicable. - - - Obtain a bulk update lock for the duration of the bulk copy operation. When not specified, row locks are used. - - - When specified, each batch of the bulk-copy operation will occur within a transaction. If you indicate this option and also provide a - object to the constructor, an occurs. - - - + + + + + Bitwise flag that specifies one or more options to use with an instance of . + + + + You can use the enumeration when you construct a instance to change how the methods for that instance behave. + + + + + The following console application demonstrates how to perform a bulk load that copies the value in the identity column of the source table to the corresponding column in the destination table, instead of generating a new value for each row's identity column. + + + To see how the option changes the way the bulk load works, run the sample with the dbo.BulkCopyDemoMatchingColumns table empty. All rows load from the source. Next, run the sample again without emptying the table. An exception is thrown, and the code writes a message to the console window notifying you that rows were not added because of primary key violations. + + + This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. + + + This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data. + + + + using System; + using System.Data; + using Microsoft.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;"; + } + } + + + + + + + When specified, AllowEncryptedValueModifications enables bulk copying of encrypted data between tables or databases, without decrypting the data. Typically, an application would select data from encrypted columns from one table without decrypting the data (the app would connect to the database with the column encryption setting keyword set to disabled) and then would use this option to bulk insert the data, which is still encrypted. + + + Use caution when specifying AllowEncryptedValueModifications as this may lead to corrupting the database because the driver does not check if the data is indeed encrypted, or if it is correctly encrypted using the same encryption type, algorithm and key as the target column. + + + + + + Check constraints while data is being inserted. By default, constraints are not checked. + + + + + Use the default values for all options. + + + + + When specified, cause the server to fire the insert triggers for the rows being inserted into the database. + + + + + Preserve source identity values. When not specified, identity values are assigned by the destination. + + + + + Preserve null values in the destination table regardless of the settings for default values. When not specified, null values are replaced by default values where applicable. + + + + + Obtain a bulk update lock for the duration of the bulk copy operation. When not specified, row locks are used. + + + + + When specified, each batch of the bulk-copy operation will occur within a transaction. If you indicate this option and also provide a object to the constructor, an occurs. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml index 3711bbb7f7..16e96e4d01 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml @@ -1,312 +1,497 @@ - - + - A guid value used to correlate before, after and error events. + + A guid value used to correlate before, after and error events. + - The name of the operation. + + The name of the operation. + - The timestamp of the event. + + The timestamp of the event. + Gets the element at the specified index in the read-only list. - The zero-based index of the element to get. - The element at the specified index in the read-only list. - + + The zero-based index of the element to get. + + + The element at the specified index in the read-only list. + + - Gets the number of elements in the collection. - The number of elements in the collection. + + Gets the number of elements in the collection. + + + The number of elements in the collection. + - Returns an enumerator that iterates through the collection. - An enumerator that can be used to iterate through the collection. + + Returns an enumerator that iterates through the collection. + + + An enumerator that can be used to iterate through the collection. + - Contains diagnostic information emitted before a command is executed. + + Contains diagnostic information emitted before a command is executed. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - A nullable guid uniquely identifying the connection that the xommand is being executed on. + + A nullable guid uniquely identifying the connection that the xommand is being executed on. + - A nullable long uniquely identifying the transaction that the command enrolled in if it is enrolled in one. + + A nullable long uniquely identifying the transaction that the command enrolled in if it is enrolled in one. + - The command object that is executing. + + The command object that is executing. + - Contains diagnostic information emitted after a command is successfully executed. + + Contains diagnostic information emitted after a command is successfully executed. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - A nullable guid uniquely identifying the connection that the command is being executed on. + + A nullable guid uniquely identifying the connection that the command is being executed on. + - A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + + A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + - The command object that is executing. + + The command object that is executing. + - An IDictionary of statistic information about the event that has completed. + + An IDictionary of statistic information about the event that has completed. + - Contains diagnostic information emitted after a command execution fails with an exception. + + Contains diagnostic information emitted after a command execution fails with an exception. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - A nullable guid uniquely identifying the connection that the command is being executed on. + + A nullable guid uniquely identifying the connection that the command is being executed on. + - A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + + A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + - The command object that is executing. + + The command object that is executing. + - The exception object that caused the command execution to fail. + + The exception object that caused the command execution to fail. + - Contains diagnostic information emitted before a connection is opened. + + Contains diagnostic information emitted before a connection is opened. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that is being opened. + + The connection object that is being opened. + - The version of the SqlClient library. + + The version of the SqlClient library. + - Contains diagnostic information emitted after a connection has been successfully opened. + + Contains diagnostic information emitted after a connection has been successfully opened. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that has been opened. + + The connection object that has been opened. + - The version of the SqlClient library. + + The version of the SqlClient library. + - The unique guid assigned to the connection. + + The unique guid assigned to the connection. + - An IDictionary of statistic information about the event that has completed. + + An IDictionary of statistic information about the event that has completed. + - Contains diagnostic information emitted after a connection open fails with an exception. + + Contains diagnostic information emitted after a connection open fails with an exception. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that has been opened. + + The connection object that has been opened. + - The version of the SqlClient library. + + The version of the SqlClient library. + - The unique guid assigned to the connection. + + The unique guid assigned to the connection. + - The exception object that caused the command execution to fail. + + The exception object that caused the command execution to fail. + - Contains diagnostic information emitted before a connection is closed. + + Contains diagnostic information emitted before a connection is closed. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that is being closed. + + The connection object that is being closed. + - The unique guid assigned to the connection. + + The unique guid assigned to the connection. + - An IDictionary of statistic information about the connection. + + An IDictionary of statistic information about the connection. + - Contains diagnostic information emitted after a connection has been successfully closed. + + Contains diagnostic information emitted after a connection has been successfully closed. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that has been closed. + + The connection object that has been closed. + - The unique guid assigned to the connection. + + The unique guid assigned to the connection. + - An IDictionary of statistic information about the connection. + + An IDictionary of statistic information about the connection. + - Contains diagnostic information emitted after a connection close fails with an exception. + + Contains diagnostic information emitted after a connection close fails with an exception. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that has been closed. + + The connection object that has been closed. + - The unique guid assigned to the connection. + + The unique guid assigned to the connection. + - An IDictionary of statistic information about the connection. + + An IDictionary of statistic information about the connection. + - The exception object that caused the command execution to fail. + + The exception object that caused the command execution to fail. + - Contains diagnostic information emitted before a transaction is opened. + + Contains diagnostic information emitted before a transaction is opened. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that the transaction belongs to. + + The connection object that the transaction belongs to. + - The IsolationLevel of the transaction. + + The IsolationLevel of the transaction. + - A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + + A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + - Contains diagnostic information emitted after a transaction is successfully committed. + + Contains diagnostic information emitted after a transaction is successfully committed. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that the transaction belongs to. + + The connection object that the transaction belongs to. + - The IsolationLevel of the transaction. + + The IsolationLevel of the transaction. + - A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + + A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + - Contains diagnostic information emitted after a transaction commit fails with an exception. + + Contains diagnostic information emitted after a transaction commit fails with an exception. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that the transaction belongs to. + + The connection object that the transaction belongs to. + - The IsolationLevel of the transaction. + + The IsolationLevel of the transaction. + - A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + + A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + - The exception object that caused the command execution to fail. + + The exception object that caused the command execution to fail. + - Contains diagnostic information emitted before a transaction rollback is rolled back. + + Contains diagnostic information emitted before a transaction rollback is rolled back. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that the transaction belongs to. + + The connection object that the transaction belongs to. + - The IsolationLevel of the transaction. + + The IsolationLevel of the transaction. + - A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + + A nullable long uniquely identifying the transaction that the command is enrolled in if it is enrolled in one, or null. + - The name of the transaction which is being rolled back. + + The name of the transaction which is being rolled back. + - Contains diagnostic information emitted after a transaction is rolled back successfully. + + Contains diagnostic information emitted after a transaction is rolled back successfully. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that the transaction belongs to. + + The connection object that the transaction belongs to. + - The IsolationLevel of the transaction. + + The IsolationLevel of the transaction. + - A nullable long uniquely identifying the transaction, or null. + + A nullable long uniquely identifying the transaction, or null. + - The name of the transaction which is being rolled back. + + The name of the transaction which is being rolled back. + - Contains diagnostic information emitted after a transaction roll back failes with an exception. + + Contains diagnostic information emitted after a transaction roll back failes with an exception. + - The name of the event that needs to be enabled for the event to be raised. + + The name of the event that needs to be enabled for the event to be raised. + - The connection object that the transaction belongs to. + + The connection object that the transaction belongs to. + - The IsolationLevel of the transaction. + + The IsolationLevel of the transaction. + - A nullable long uniquely identifying the transaction , or null. + + A nullable long uniquely identifying the transaction , or null. + - The name of the transaction which is being rolled back. + + The name of the transaction which is being rolled back. + - The exception object that caused the command execution to fail. + + The exception object that caused the command execution to fail. + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientFactory.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientFactory.xml index 3947acf211..ff41a4f383 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientFactory.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientFactory.xml @@ -1,331 +1,290 @@ - - - - - Represents a set of methods for creating instances of the - - provider's implementation of the data source classes. - - - To be added. - - - - - Gets a value that indicates whether a - - can be created. - - - - if a - - can be created; otherwise, - - . - - - class provides the property so that inheritors can indicate -whether they can provide a data source enumerator. The displays this property, but its value is always `true`. - -## Examples -The following example displays a list of all available SQL Server data sources, using code that could enumerate data sources for any provider. - -[!code-csharp[SqlClientFactory.DataSourceEnumerator#1](~/../sqlclient/doc/samples/SqlClientFactory_DataSourceEnumerator.cs#1)] -]]> - - + + + + + Represents a set of methods for creating instances of the provider's implementation of the data source classes. + + + + + Gets a value that indicates whether a can be created. + + + if a can be created; otherwise, . + + + The class provides the property so that inheritors can indicate whether they can provide a data source enumerator. The displays this property, but its value is always . + + + + The following example displays a list of all available SQL Server data sources, using code that could enumerate data sources for any provider. + + + + using System; + using System.Data; + using System.Data.Common; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + // List all SQL Server instances: + ListServers(SqlClientFactory.Instance); + + Console.WriteLine(); + Console.WriteLine("Press any key to continue..."); + Console.ReadKey(); + } + private static void ListServers(DbProviderFactory factory) + { + // This procedure is provider-agnostic, and can list + // instances of any provider's servers. Of course, + // not all providers can create a data source enumerator, + // so it's best to check the CanCreateDataSourceEnumerator + // property before attempting to list the data sources. + if (factory.CanCreateDataSourceEnumerator) + { + DbDataSourceEnumerator instance = + factory.CreateDataSourceEnumerator(); + DataTable table = instance.GetDataSources(); + + foreach (DataRow row in table.Rows) + { + Console.WriteLine("{0}\\{1}", + row["ServerName"], row["InstanceName"]); + } + } + } + } + + + - Gets a value that indicates whether a - - can be created. + Gets a value that indicates whether a can be created. - - if a - - can be created; otherwise, - - . + if a can be created; otherwise, . - - class provides the property so that inheritors can indicate -whether they can provide a DbBatch. The displays this property, but its value is always `true`. -]]> - + The class provides the property so that inheritors can indicate whether they can provide a DbBatch. The displays this property, but its value is always true. - - - Returns a strongly typed - - instance. - - - A new strongly typed instance of - - . - - - instance: - - -```csharp -SqlClientFactory newFactory = SqlClientFactory.Instance; -DbCommand cmd = newFactory.CreateCommand(); -``` -]]> - - - - - Returns a strongly typed - - instance. - - - A new strongly typed instance of - - . - - - instance: - - -```csharp -SqlClientFactory newFactory = SqlClientFactory.Instance; -DbCommandBuilder cmd = newFactory.CreateCommandBuilder(); -``` -]]> - - - - - Returns a strongly typed - - instance. - - - A new strongly typed instance of - - . - - - instance: - - -```csharp -SqlClientFactory newFactory = SqlClientFactory.Instance; -DbConnection cmd = newFactory.CreateConnection(); - -``` -]]> - - - - - Returns a strongly typed - - instance. - - - A new strongly typed instance of - - . - - - instance: - -```csharp -SqlClientFactory newFactory = SqlClientFactory.Instance; -DbConnectionStringBuilder cmd = -newFactory.CreateConnectionStringBuilder(); -``` -]]> - - - - - Returns a strongly typed - - instance. - - - A new strongly typed instance of - - . - - - instance: - -```csharp -SqlClientFactory newFactory = SqlClientFactory.Instance; -DbDataAdapter cmd = newFactory.CreateDataAdapter(); -``` -]]> - - - - - Returns a new - - . - - - A new data source enumerator. - - - - - - - - Returns a strongly typed - - instance. - - - A new strongly typed instance of - - . - - - instance: - - -```csharp -SqlClientFactory newFactory = SqlClientFactory.Instance; -DbParameter cmd = newFactory.CreateParameter(); -``` -]]> - - - - - A member of the - - enumeration. - - - Returns a new - - . - - - A strongly typed instance of - - . - - - To be added. - - - + - Returns a strongly typed - - instance. + Returns a strongly typed instance. - A new strongly typed instance of - - . + A new strongly typed instance of . + + + + The following code fragment returns a strongly typed instance: + + + SqlClientFactory newFactory = SqlClientFactory.Instance; + DbCommand cmd = newFactory.CreateCommand(); + + + + + + Returns a strongly typed instance. + + + A new strongly typed instance of . + + + + The following code fragment returns a strongly typed instance: + + + SqlClientFactory newFactory = SqlClientFactory.Instance; + DbCommandBuilder cmd = newFactory.CreateCommandBuilder(); + + + + + + Returns a strongly typed instance. + + + A new strongly typed instance of . - - instance: - - -```csharp -SqlClientFactory newFactory = SqlClientFactory.Instance; -DbParameter cmd = newFactory.CreateBatch(); -``` -]]> - + + The following code fragment returns a strongly typed instance: + + + SqlClientFactory newFactory = SqlClientFactory.Instance; + DbConnection cmd = newFactory.CreateConnection(); + + + + + Returns a strongly typed instance. + + + A new strongly typed instance of . + + + + The following code fragment returns a strongly typed instance: + + + SqlClientFactory newFactory = SqlClientFactory.Instance; + DbConnectionStringBuilder cmd = newFactory.CreateConnectionStringBuilder(); + + + + + + Returns a strongly typed instance. + + + A new strongly typed instance of . + + + + The following code fragment returns a strongly typed instance: + + + SqlClientFactory newFactory = SqlClientFactory.Instance; + DbDataAdapter cmd = newFactory.CreateDataAdapter(); + + + + + + Returns a new . + + + A new data source enumerator. + + + + The following example displays a list of all available SQL Server data sources, using code that could enumerate data sources for any provider. + + + + using System; + using System.Data; + using System.Data.Common; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + // List all SQL Server instances: + ListServers(SqlClientFactory.Instance); + + Console.WriteLine(); + Console.WriteLine("Press any key to continue..."); + Console.ReadKey(); + } + private static void ListServers(DbProviderFactory factory) + { + // This procedure is provider-agnostic, and can list + // instances of any provider's servers. Of course, + // not all providers can create a data source enumerator, + // so it's best to check the CanCreateDataSourceEnumerator + // property before attempting to list the data sources. + if (factory.CanCreateDataSourceEnumerator) + { + DbDataSourceEnumerator instance = + factory.CreateDataSourceEnumerator(); + DataTable table = instance.GetDataSources(); + + foreach (DataRow row in table.Rows) + { + Console.WriteLine("{0}\\{1}", + row["ServerName"], row["InstanceName"]); + } + } + } + } + + + + + + Returns a strongly typed instance. + + + A new strongly typed instance of . + + + + The following code fragment returns a strongly typed instance: + + + SqlClientFactory newFactory = SqlClientFactory.Instance; + DbParameter cmd = newFactory.CreateParameter(); + + + + + + A member of the enumeration. + + + Returns a new . + + + A strongly typed instance of . + + + + + Returns a strongly typed instance. + + + A new strongly typed instance of . + + + + The following code fragment returns a strongly typed instance: + + + SqlClientFactory newFactory = SqlClientFactory.Instance; + DbParameter cmd = newFactory.CreateBatch(); + + - Returns a strongly typed - - instance. + Returns a strongly typed instance. - A new strongly typed instance of - - . + A new strongly typed instance of . - - - instance: - - -```csharp -SqlClientFactory newFactory = SqlClientFactory.Instance; -DbParameter cmd = newFactory.CreateBatchCommand(); -``` -]]> - - + + + The following code fragment returns a strongly typed instance: + + + SqlClientFactory newFactory = SqlClientFactory.Instance; + DbParameter cmd = newFactory.CreateBatchCommand(); + + - - - Gets an instance of the - - . This can be used to retrieve strongly typed data objects. - - - property to retrieve a **SqlClientFactory** instance, and then return a strongly typed - instance: - - -```csharp -SqlClientFactory newFactory = SqlClientFactory.Instance; -DbCommand cmd = newFactory.CreateCommand(); -``` -]]> - - - + + + Gets an instance of the . This can be used to retrieve strongly typed data objects. + + + + The following code fragment uses the property to retrieve a instance, and then return a strongly typed instance: + + + SqlClientFactory newFactory = SqlClientFactory.Instance; + DbCommand cmd = newFactory.CreateCommand(); + + + + diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlBulkCopyColumnMapping.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlBulkCopyColumnMapping.cs index 2f6ef5c532..734e0615a7 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlBulkCopyColumnMapping.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlBulkCopyColumnMapping.cs @@ -110,7 +110,7 @@ public SqlBulkCopyColumnMapping(string sourceColumn, string destinationColumn) DestinationColumn = destinationColumn; } - /// + /// public SqlBulkCopyColumnMapping(int sourceColumnOrdinal, string destinationColumn) { SourceOrdinal = sourceColumnOrdinal; From fe4a848f3233a7492b70e5ac5560fa6f2c5bab2e Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 5 Sep 2024 13:11:07 -0500 Subject: [PATCH 2/4] Reverting removal of the snippet files. --- doc/samples/SqlBatch_ExecuteReader.cs | 46 +++++ doc/samples/SqlBulkCopy_BatchSize.cs | 79 ++++++++ doc/samples/SqlBulkCopy_ColumnMapping.cs | 92 +++++++++ .../SqlBulkCopy_ColumnMappingColNameIndex.cs | 85 +++++++++ .../SqlBulkCopy_ColumnMappingCollection.cs | 85 +++++++++ ...BulkCopy_ColumnMappingCollectionOrdinal.cs | 85 +++++++++ ...BulkCopy_ColumnMappingDestinationColumn.cs | 95 ++++++++++ ...ulkCopy_ColumnMappingDestinationOrdinal.cs | 95 ++++++++++ .../SqlBulkCopy_ColumnMappingIndexColName.cs | 85 +++++++++ .../SqlBulkCopy_ColumnMappingNameOrdinal.cs | 92 +++++++++ .../SqlBulkCopy_ColumnMappingOrdersDetails.cs | 168 +++++++++++++++++ .../SqlBulkCopy_ColumnMappingOrdinal.cs | 92 +++++++++ .../SqlBulkCopy_ColumnMappingOrdinalName.cs | 92 +++++++++ .../SqlBulkCopy_ColumnMappingRemove.cs | 168 +++++++++++++++++ .../SqlBulkCopy_ColumnMappingRemoveAt.cs | 171 +++++++++++++++++ doc/samples/SqlBulkCopy_ColumnOrderHint.cs | 84 +++++++++ .../SqlBulkCopy_ColumnOrderHintCollection.cs | 83 ++++++++ ...qlBulkCopy_ColumnOrderHintCollectionAdd.cs | 86 +++++++++ ...lBulkCopy_ColumnOrderHintCollectionAdd2.cs | 83 ++++++++ ...BulkCopy_ColumnOrderHintCollectionClear.cs | 177 ++++++++++++++++++ ...ulkCopy_ColumnOrderHintCollectionRemove.cs | 176 +++++++++++++++++ ...kCopy_ColumnOrderHintCollectionRemoveAt.cs | 176 +++++++++++++++++ .../SqlBulkCopy_ColumnOrderHintColumn.cs | 85 +++++++++ .../SqlBulkCopy_ColumnOrderHintSortOrder.cs | 85 +++++++++ doc/samples/SqlBulkCopy_ConnectionString.cs | 81 ++++++++ doc/samples/SqlBulkCopy_DataTable.cs | 116 ++++++++++++ doc/samples/SqlBulkCopy_KeepIdentity.cs | 82 ++++++++ doc/samples/SqlBulkCopy_NotifyAfter.cs | 91 +++++++++ doc/samples/SqlBulkCopy_OrdersDetails.cs | 154 +++++++++++++++ doc/samples/SqlBulkCopy_RowArray.cs | 120 ++++++++++++ doc/samples/SqlBulkCopy_Single.cs | 92 +++++++++ .../SqlClientFactory_DataSourceEnumerator.cs | 39 ++++ 32 files changed, 3340 insertions(+) create mode 100644 doc/samples/SqlBatch_ExecuteReader.cs create mode 100644 doc/samples/SqlBulkCopy_BatchSize.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMapping.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingCollection.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingRemove.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHint.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs create mode 100644 doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs create mode 100644 doc/samples/SqlBulkCopy_ConnectionString.cs create mode 100644 doc/samples/SqlBulkCopy_DataTable.cs create mode 100644 doc/samples/SqlBulkCopy_KeepIdentity.cs create mode 100644 doc/samples/SqlBulkCopy_NotifyAfter.cs create mode 100644 doc/samples/SqlBulkCopy_OrdersDetails.cs create mode 100644 doc/samples/SqlBulkCopy_RowArray.cs create mode 100644 doc/samples/SqlBulkCopy_Single.cs create mode 100644 doc/samples/SqlClientFactory_DataSourceEnumerator.cs diff --git a/doc/samples/SqlBatch_ExecuteReader.cs b/doc/samples/SqlBatch_ExecuteReader.cs new file mode 100644 index 0000000000..a25bd9da34 --- /dev/null +++ b/doc/samples/SqlBatch_ExecuteReader.cs @@ -0,0 +1,46 @@ +// +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string str = "Data Source=(local);Initial Catalog=Northwind;" + + "Integrated Security=SSPI;Encrypt=False"; + RunBatch(str); + } + + static void RunBatch(string connString) + { + using var connection = new SqlConnection(connString); + connection.Open(); + + var batch = new SqlBatch(connection); + + const int count = 10; + const string parameterName = "parameter"; + for (int i = 0; i < count; i++) + { + var batchCommand = new SqlBatchCommand($"SELECT @{parameterName} as value"); + batchCommand.Parameters.Add(new SqlParameter(parameterName, i)); + batch.BatchCommands.Add(batchCommand); + } + + // Optionally Prepare + batch.Prepare(); + + var results = new List(count); + using (SqlDataReader reader = batch.ExecuteReader()) + { + do + { + while (reader.Read()) + { + results.Add(reader.GetFieldValue(0)); + } + } while (reader.NextResult()); + } + Console.WriteLine(string.Join(", ", results)); + } +} +// diff --git a/doc/samples/SqlBulkCopy_BatchSize.cs b/doc/samples/SqlBulkCopy_BatchSize.cs new file mode 100644 index 0000000000..ee0a62b53c --- /dev/null +++ b/doc/samples/SqlBulkCopy_BatchSize.cs @@ -0,0 +1,79 @@ +using Microsoft.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. + // 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)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Set the BatchSize. + bulkCopy.BatchSize = 50; + + 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;"; + } +} diff --git a/doc/samples/SqlBulkCopy_ColumnMapping.cs b/doc/samples/SqlBulkCopy_ColumnMapping.cs new file mode 100644 index 0000000000..6908e2bbdd --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMapping.cs @@ -0,0 +1,92 @@ +// +using System; +using System.Data; +using Microsoft.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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs b/doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs new file mode 100644 index 0000000000..9c1e797bc8 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs @@ -0,0 +1,85 @@ +using System; +using System.Data; +// +using Microsoft.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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs b/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs new file mode 100644 index 0000000000..4cf90008c6 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs @@ -0,0 +1,85 @@ +// +using System; +using System.Data; +using Microsoft.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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs b/doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs new file mode 100644 index 0000000000..fa0db0ef4c --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs @@ -0,0 +1,85 @@ +// +using System; +using System.Data; +using Microsoft.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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs b/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs new file mode 100644 index 0000000000..d46a58a261 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs @@ -0,0 +1,95 @@ +using System; +using System.Data; +// +using Microsoft.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 source and destination. + SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(); + mapID.SourceColumn = "ProductID"; + mapID.DestinationColumn = "ProdID"; + bulkCopy.ColumnMappings.Add(mapID); + + SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping(); + mapName.SourceColumn = "Name"; + mapName.DestinationColumn = "ProdName"; + bulkCopy.ColumnMappings.Add(mapName); + + SqlBulkCopyColumnMapping mapNumber = new SqlBulkCopyColumnMapping(); + mapNumber.SourceColumn = "ProductNumber"; + mapNumber.DestinationColumn = "ProdNum"; + bulkCopy.ColumnMappings.Add(mapNumber); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs b/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs new file mode 100644 index 0000000000..19e31f282d --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs @@ -0,0 +1,95 @@ +using System; +using System.Data; +// +using Microsoft.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 source and destination. + SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(); + mapID.SourceOrdinal = 0; + mapID.DestinationOrdinal = 0; + bulkCopy.ColumnMappings.Add(mapID); + + SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping(); + mapName.SourceOrdinal = 1; + mapName.DestinationOrdinal = 2; + bulkCopy.ColumnMappings.Add(mapName); + + SqlBulkCopyColumnMapping mapNumber = new SqlBulkCopyColumnMapping(); + mapNumber.SourceOrdinal = 2; + mapNumber.DestinationOrdinal = 1; + bulkCopy.ColumnMappings.Add(mapNumber); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs b/doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs new file mode 100644 index 0000000000..fa0db0ef4c --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs @@ -0,0 +1,85 @@ +// +using System; +using System.Data; +using Microsoft.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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs b/doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs new file mode 100644 index 0000000000..bdda864974 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs @@ -0,0 +1,92 @@ +using System; +using System.Data; +// +using Microsoft.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 and ordinal. + SqlBulkCopyColumnMapping columnMapID = + new SqlBulkCopyColumnMapping("ProductID", 0); + bulkCopy.ColumnMappings.Add(columnMapID); + + SqlBulkCopyColumnMapping columnMapName = + new SqlBulkCopyColumnMapping("Name", 2); + bulkCopy.ColumnMappings.Add(columnMapName); + + SqlBulkCopyColumnMapping columnMapNumber = + new SqlBulkCopyColumnMapping("ProductNumber", 1); + bulkCopy.ColumnMappings.Add(columnMapNumber); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs b/doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs new file mode 100644 index 0000000000..a488c621bc --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs @@ -0,0 +1,168 @@ +using System; +using System.Data; +// +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = + new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + { + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs b/doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs new file mode 100644 index 0000000000..671383133f --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs @@ -0,0 +1,92 @@ +using System; +using System.Data; +// +using Microsoft.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 ordinal. + SqlBulkCopyColumnMapping columnMapID = + new SqlBulkCopyColumnMapping(0, 0); + bulkCopy.ColumnMappings.Add(columnMapID); + + SqlBulkCopyColumnMapping columnMapName = + new SqlBulkCopyColumnMapping(1, 2); + bulkCopy.ColumnMappings.Add(columnMapName); + + SqlBulkCopyColumnMapping columnMapNumber = + new SqlBulkCopyColumnMapping(2, 1); + bulkCopy.ColumnMappings.Add(columnMapNumber); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs b/doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs new file mode 100644 index 0000000000..8ca91ee00e --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs @@ -0,0 +1,92 @@ +using System; +using System.Data; +// +using Microsoft.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 ordinal and name. + SqlBulkCopyColumnMapping columnMapID = + new SqlBulkCopyColumnMapping(0, "ProdID"); + bulkCopy.ColumnMappings.Add(columnMapID); + + SqlBulkCopyColumnMapping columnMapName = + new SqlBulkCopyColumnMapping(1, "ProdName"); + bulkCopy.ColumnMappings.Add(columnMapName); + + SqlBulkCopyColumnMapping columnMapNumber = + new SqlBulkCopyColumnMapping(2, "ProdNum"); + bulkCopy.ColumnMappings.Add(columnMapNumber); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingRemove.cs b/doc/samples/SqlBulkCopy_ColumnMappingRemove.cs new file mode 100644 index 0000000000..f5dc29e254 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingRemove.cs @@ -0,0 +1,168 @@ +// +using System; +using System.Data; +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = + new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + { + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs b/doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs new file mode 100644 index 0000000000..9d8091965d --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs @@ -0,0 +1,171 @@ +using System; +using System.Data; +// +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = + new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Rather than clearing mappings that are not necessary + // for the next bulk copyo peration, the unneeded mappings + // are removed with the RemoveAt method. + bulkCopy.ColumnMappings.RemoveAt(2); + bulkCopy.ColumnMappings.RemoveAt(1); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + bulkCopy.WriteToServer(readerDetail); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + { + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHint.cs b/doc/samples/SqlBulkCopy_ColumnOrderHint.cs new file mode 100644 index 0000000000..9960debf20 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnOrderHint.cs @@ -0,0 +1,84 @@ +// +using System; +using System.Data; +using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Setup an order hint for the ProductNumber column. + SqlBulkCopyColumnOrderHint hintNumber = + new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); + bulkCopy.ColumnOrderHints.Add(hintNumber); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs new file mode 100644 index 0000000000..4a92099ddb --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs @@ -0,0 +1,83 @@ +// +using System; +using System.Data; +using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Specify the sort order for the ProductNumber column in + // the destination table. + bulkCopy.ColumnOrderHints.Add("ProductNumber", SortOrder.Ascending); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs new file mode 100644 index 0000000000..2d6599d525 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs @@ -0,0 +1,86 @@ +// +using System; +using System.Data; +using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Specify the sort order for the ProductNumber column in + // the destination table. + // Setup an order hint for the ProductNumber column. + SqlBulkCopyColumnOrderHint hintNumber = + new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); + bulkCopy.ColumnOrderHints.Add(hintNumber); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs new file mode 100644 index 0000000000..4a92099ddb --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs @@ -0,0 +1,83 @@ +// +using System; +using System.Data; +using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Specify the sort order for the ProductNumber column in + // the destination table. + bulkCopy.ColumnOrderHints.Add("ProductNumber", SortOrder.Ascending); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs new file mode 100644 index 0000000000..0df1281b52 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs @@ -0,0 +1,177 @@ +// +using System; +using System.Data; +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = + new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Add order hint for OrderDate column. + bulkCopy.ColumnOrderHints.Add("OrderDate", SortOrder.Ascending); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Clear the ColumnOrderHintCollection. + bulkCopy.ColumnOrderHints.Clear(); + + // Add order hint for SalesOrderID column. + bulkCopy.ColumnOrderHints.Add("SalesOrderID", SortOrder.Ascending); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + { + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs new file mode 100644 index 0000000000..ea9a8f4a46 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs @@ -0,0 +1,176 @@ +// +using System; +using System.Data; +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = + new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Add the order hint for the OrderDate column. + SqlBulkCopyColumnOrderHint hintDate = + new SqlBulkCopyColumnOrderHint("OrderDate", SortOrder.Ascending); + bulkCopy.ColumnOrderHints.Add(hintDate); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Remove the order hint for the OrderDate column. + bulkCopy.ColumnOrderHints.Remove(hintDate); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + { + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs new file mode 100644 index 0000000000..b965599175 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs @@ -0,0 +1,176 @@ +// +using System; +using System.Data; +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = + new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Guarantee that columns are mapped correctly by + // defining the column mappings for the order. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate"); + bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber"); + + // Add the order hint for the OrderDate column. + SqlBulkCopyColumnOrderHint hintDate = + new SqlBulkCopyColumnOrderHint("OrderDate", SortOrder.Ascending); + bulkCopy.ColumnOrderHints.Add(hintDate); + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up the order details destination. + bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"; + + // Clear the ColumnMappingCollection. + bulkCopy.ColumnMappings.Clear(); + + // Add order detail column mappings. + bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID"); + bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID"); + bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty"); + bulkCopy.ColumnMappings.Add("ProductID", "ProductID"); + bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice"); + + // Remove the order hint for the OrderDate column. + bulkCopy.ColumnOrderHints.RemoveAt(0); + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + { + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs new file mode 100644 index 0000000000..6a75e0289c --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs @@ -0,0 +1,85 @@ +// +using System; +using System.Data; +using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Setup an order hint for the ProductNumber column. + SqlBulkCopyColumnOrderHint hintNumber = + new SqlBulkCopyColumnOrderHint("number", SortOrder.Ascending); + hintNumber.Column = "ProductNumber"; + bulkCopy.ColumnOrderHints.Add(hintNumber); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs b/doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs new file mode 100644 index 0000000000..54cef5da53 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs @@ -0,0 +1,85 @@ +// +using System; +using System.Data; +using Microsoft.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(); + + // Set up the bulk copy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Setup an order hint for the ProductNumber column. + SqlBulkCopyColumnOrderHint hintNumber = + new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending); + hintNumber.SortOrder = SortOrder.Descending; + bulkCopy.ColumnOrderHints.Add(hintNumber); + + // 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_ConnectionString.cs b/doc/samples/SqlBulkCopy_ConnectionString.cs new file mode 100644 index 0000000000..50c3101369 --- /dev/null +++ b/doc/samples/SqlBulkCopy_ConnectionString.cs @@ -0,0 +1,81 @@ +using System; +using System.Data; +// +using Microsoft.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(); + + // Set up the bulk copy object using a connection string. + // 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)) + { + 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_DataTable.cs b/doc/samples/SqlBulkCopy_DataTable.cs new file mode 100644 index 0000000000..a3c8c98fae --- /dev/null +++ b/doc/samples/SqlBulkCopy_DataTable.cs @@ -0,0 +1,116 @@ +using System; +using System.Data; +// +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = + new SqlConnection(connectionString)) + { + connection.Open(); + + // Perform an initial count on the destination table. + SqlCommand commandRowCount = new SqlCommand( + "SELECT COUNT(*) FROM " + + "dbo.BulkCopyDemoMatchingColumns;", + connection); + long countStart = System.Convert.ToInt32( + commandRowCount.ExecuteScalar()); + Console.WriteLine("Starting row count = {0}", countStart); + + // Create a table with some rows. + DataTable newProducts = MakeTable(); + + // Create the SqlBulkCopy object. + // Note that the column positions in the source DataTable + // match the column positions in the destination table so + // there is no need to map columns. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + try + { + // Write from the source to the destination. + bulkCopy.WriteToServer(newProducts); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + // 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 DataTable MakeTable() + // Create a new DataTable named NewProducts. + { + DataTable newProducts = new DataTable("NewProducts"); + + // Add three column objects to the table. + DataColumn productID = new DataColumn(); + productID.DataType = System.Type.GetType("System.Int32"); + productID.ColumnName = "ProductID"; + productID.AutoIncrement = true; + newProducts.Columns.Add(productID); + + DataColumn productName = new DataColumn(); + productName.DataType = System.Type.GetType("System.String"); + productName.ColumnName = "Name"; + newProducts.Columns.Add(productName); + + DataColumn productNumber = new DataColumn(); + productNumber.DataType = System.Type.GetType("System.String"); + productNumber.ColumnName = "ProductNumber"; + newProducts.Columns.Add(productNumber); + + // Create an array for DataColumn objects. + DataColumn[] keys = new DataColumn[1]; + keys[0] = productID; + newProducts.PrimaryKey = keys; + + // Add some new rows to the collection. + DataRow row = newProducts.NewRow(); + row["Name"] = "CC-101-WH"; + row["ProductNumber"] = "Cyclocomputer - White"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-BK"; + row["ProductNumber"] = "Cyclocomputer - Black"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-ST"; + row["ProductNumber"] = "Cyclocomputer - Stainless"; + newProducts.Rows.Add(row); + newProducts.AcceptChanges(); + + // Return the new DataTable. + return newProducts; + } + private static string GetConnectionString() + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + { + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_KeepIdentity.cs b/doc/samples/SqlBulkCopy_KeepIdentity.cs new file mode 100644 index 0000000000..da85715725 --- /dev/null +++ b/doc/samples/SqlBulkCopy_KeepIdentity.cs @@ -0,0 +1,82 @@ +using System; +using System.Data; +// +using Microsoft.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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_NotifyAfter.cs b/doc/samples/SqlBulkCopy_NotifyAfter.cs new file mode 100644 index 0000000000..fb01bb9a5c --- /dev/null +++ b/doc/samples/SqlBulkCopy_NotifyAfter.cs @@ -0,0 +1,91 @@ +using System; +using System.Data; +// +using Microsoft.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("NotifyAfter Sample"); + 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. + // 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)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + // Set up the event handler to notify after 50 rows. + bulkCopy.SqlRowsCopied += + new SqlRowsCopiedEventHandler(OnSqlRowsCopied); + bulkCopy.NotifyAfter = 50; + + 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 void OnSqlRowsCopied( + object sender, SqlRowsCopiedEventArgs e) + { + Console.WriteLine("Copied {0} so far...", e.RowsCopied); + } + 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;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_OrdersDetails.cs b/doc/samples/SqlBulkCopy_OrdersDetails.cs new file mode 100644 index 0000000000..9fd713a548 --- /dev/null +++ b/doc/samples/SqlBulkCopy_OrdersDetails.cs @@ -0,0 +1,154 @@ +using System; +using System.Data; +// +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = + new SqlConnection(connectionString)) + { + connection.Open(); + + // Empty the destination tables. + SqlCommand deleteHeader = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderHeader;", + connection); + deleteHeader.ExecuteNonQuery(); + SqlCommand deleteDetail = new SqlCommand( + "DELETE FROM dbo.BulkCopyDemoOrderDetail;", + connection); + deleteDetail.ExecuteNonQuery(); + + // Perform an initial count on the destination + // table with matching columns. + SqlCommand countRowHeader = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", + connection); + long countStartHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Header table = {0}", + countStartHeader); + + // Perform an initial count on the destination + // table with different column positions. + SqlCommand countRowDetail = new SqlCommand( + "SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", + connection); + long countStartDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine( + "Starting row count for Detail table = {0}", + countStartDetail); + + // Get data from the source table as a SqlDataReader. + // The Sales.SalesOrderHeader and Sales.SalesOrderDetail + // tables are quite large and could easily cause a timeout + // if all data from the tables is added to the destination. + // To keep the example simple and quick, a parameter is + // used to select only orders for a particular account + // as the source for the bulk insert. + SqlCommand headerData = new SqlCommand( + "SELECT [SalesOrderID], [OrderDate], " + + "[AccountNumber] FROM [Sales].[SalesOrderHeader] " + + "WHERE [AccountNumber] = @accountNumber;", + connection); + SqlParameter parameterAccount = new SqlParameter(); + parameterAccount.ParameterName = "@accountNumber"; + parameterAccount.SqlDbType = SqlDbType.NVarChar; + parameterAccount.Direction = ParameterDirection.Input; + parameterAccount.Value = "10-4020-000034"; + headerData.Parameters.Add(parameterAccount); + SqlDataReader readerHeader = headerData.ExecuteReader(); + + // Get the Detail data in a separate connection. + using (SqlConnection connection2 = new SqlConnection(connectionString)) + { + connection2.Open(); + SqlCommand sourceDetailData = new SqlCommand( + "SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " + + "[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " + + "INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." + + "[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " + + "WHERE [AccountNumber] = @accountNumber;", connection2); + + SqlParameter accountDetail = new SqlParameter(); + accountDetail.ParameterName = "@accountNumber"; + accountDetail.SqlDbType = SqlDbType.NVarChar; + accountDetail.Direction = ParameterDirection.Input; + accountDetail.Value = "10-4020-000034"; + sourceDetailData.Parameters.Add(accountDetail); + SqlDataReader readerDetail = sourceDetailData.ExecuteReader(); + + // Create the SqlBulkCopy object. + using (SqlBulkCopy bulkCopy = + new SqlBulkCopy(connectionString)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderHeader"; + + // Write readerHeader to the destination. + try + { + bulkCopy.WriteToServer(readerHeader); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerHeader.Close(); + } + + // Set up a different destination and + // map columns. + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoOrderDetail"; + + // Write readerDetail to the destination. + try + { + bulkCopy.WriteToServer(readerDetail); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + readerDetail.Close(); + } + } + + // Perform a final count on the destination + // tables to see how many rows were added. + long countEndHeader = System.Convert.ToInt32( + countRowHeader.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Header table.", + countEndHeader - countStartHeader); + long countEndDetail = System.Convert.ToInt32( + countRowDetail.ExecuteScalar()); + Console.WriteLine("{0} rows were added to the Detail table.", + countEndDetail - countStartDetail); + Console.WriteLine("Press Enter to finish."); + Console.ReadLine(); + } + } + } + + private static string GetConnectionString() + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + { + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_RowArray.cs b/doc/samples/SqlBulkCopy_RowArray.cs new file mode 100644 index 0000000000..cce09d0233 --- /dev/null +++ b/doc/samples/SqlBulkCopy_RowArray.cs @@ -0,0 +1,120 @@ +using System; +using System.Data; +// +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = GetConnectionString(); + // Open a connection to the AdventureWorks database. + using (SqlConnection connection = + new SqlConnection(connectionString)) + { + connection.Open(); + + // Perform an initial count on the destination table. + SqlCommand commandRowCount = new SqlCommand( + "SELECT COUNT(*) FROM " + + "dbo.BulkCopyDemoMatchingColumns;", + connection); + long countStart = System.Convert.ToInt32( + commandRowCount.ExecuteScalar()); + Console.WriteLine("Starting row count = {0}", countStart); + + // Create a table with some rows. + DataTable newProducts = MakeTable(); + + // Get a reference to a single row in the table. + DataRow[] rowArray = newProducts.Select( + "Name='CC-101-BK'"); + + // Create the SqlBulkCopy object. + // Note that the column positions in the source DataTable + // match the column positions in the destination table so + // there is no need to map columns. + using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) + { + bulkCopy.DestinationTableName = + "dbo.BulkCopyDemoMatchingColumns"; + + try + { + // Write the array of rows to the destination. + bulkCopy.WriteToServer(rowArray); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + // 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 DataTable MakeTable() + // Create a new DataTable named NewProducts. + { + DataTable newProducts = new DataTable("NewProducts"); + + // Add three column objects to the table. + DataColumn productID = new DataColumn(); + productID.DataType = System.Type.GetType("System.Int32"); + productID.ColumnName = "ProductID"; + productID.AutoIncrement = true; + newProducts.Columns.Add(productID); + + DataColumn productName = new DataColumn(); + productName.DataType = System.Type.GetType("System.String"); + productName.ColumnName = "Name"; + newProducts.Columns.Add(productName); + + DataColumn productNumber = new DataColumn(); + productNumber.DataType = System.Type.GetType("System.String"); + productNumber.ColumnName = "ProductNumber"; + newProducts.Columns.Add(productNumber); + + // Create an array for DataColumn objects. + DataColumn[] keys = new DataColumn[1]; + keys[0] = productID; + newProducts.PrimaryKey = keys; + + // Add some new rows to the collection. + DataRow row = newProducts.NewRow(); + row["Name"] = "CC-101-WH"; + row["ProductNumber"] = "Cyclocomputer - White"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-BK"; + row["ProductNumber"] = "Cyclocomputer - Black"; + + newProducts.Rows.Add(row); + row = newProducts.NewRow(); + row["Name"] = "CC-101-ST"; + row["ProductNumber"] = "Cyclocomputer - Stainless"; + newProducts.Rows.Add(row); + newProducts.AcceptChanges(); + + // Return the new DataTable. + return newProducts; + } + private static string GetConnectionString() + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + { + return "Data Source=(local); " + + " Integrated Security=true;" + + "Initial Catalog=AdventureWorks;"; + } +} +// diff --git a/doc/samples/SqlBulkCopy_Single.cs b/doc/samples/SqlBulkCopy_Single.cs new file mode 100644 index 0000000000..e5b7f7538e --- /dev/null +++ b/doc/samples/SqlBulkCopy_Single.cs @@ -0,0 +1,92 @@ +using System; +using System.Data; +// +using Microsoft.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;"; + } +} +// diff --git a/doc/samples/SqlClientFactory_DataSourceEnumerator.cs b/doc/samples/SqlClientFactory_DataSourceEnumerator.cs new file mode 100644 index 0000000000..f1e1a09992 --- /dev/null +++ b/doc/samples/SqlClientFactory_DataSourceEnumerator.cs @@ -0,0 +1,39 @@ +// +using System; +using System.Data; +using System.Data.Common; +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + // List all SQL Server instances: + ListServers(SqlClientFactory.Instance); + + Console.WriteLine(); + Console.WriteLine("Press any key to continue..."); + Console.ReadKey(); + } + private static void ListServers(DbProviderFactory factory) + { + // This procedure is provider-agnostic, and can list + // instances of any provider's servers. Of course, + // not all providers can create a data source enumerator, + // so it's best to check the CanCreateDataSourceEnumerator + // property before attempting to list the data sources. + if (factory.CanCreateDataSourceEnumerator) + { + DbDataSourceEnumerator instance = + factory.CreateDataSourceEnumerator(); + DataTable table = instance.GetDataSources(); + + foreach (DataRow row in table.Rows) + { + Console.WriteLine("{0}\\{1}", + row["ServerName"], row["InstanceName"]); + } + } + } +} +// From 728be39e243802124b0786d015e13771cf483392 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Tue, 10 Sep 2024 11:38:31 -0500 Subject: [PATCH 3/4] Fixing build break caused by parameter not having a comment. --- .../Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml index c5413e2194..d45c4535cf 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml @@ -135,6 +135,9 @@ The index where the object should be located. + + The object to add to the collection. + Sets the object at the specified index to a new value. From 31f8cf16e70b5b3c71e7bcf1c5c7c824cd8fa12b Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 12 Sep 2024 11:32:46 -0500 Subject: [PATCH 4/4] These changes should fix the broken comments --- .../SqlClientDiagnostic.xml | 30 ++++++++++++++++++- .../netcore/ref/Microsoft.Data.SqlClient.cs | 18 +++++------ 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml index 16e96e4d01..5ac5e9028a 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml @@ -1,5 +1,14 @@  + + Class that provides strongly-typed collection of key-value pairs for SqlClient diagnostic objects. + + + Constructs a new instance of the class. + Guid that identifies the operation for correlation of events. + Operation being performed that caused the diagnostic event. + Timestamp of when the diagnostic event occurred. + A guid value used to correlate before, after and error events. @@ -35,6 +44,9 @@ The number of elements in the collection. + + The number of common properties. + Returns an enumerator that iterates through the collection. @@ -43,6 +55,22 @@ An enumerator that can be used to iterate through the collection. + + Gets the number of properties in derived instances of that are not common to all diagnostic objects. + + + Gets a property from a derived instance of . + + + Attempts to retrieve the key-value pair diagnostic property. + Index to attempt to retrieve. + + If a key-value pair with the provided was found, this out parameter will be populated with the retrieved diagnostic property. If nothing was found, this parameter will be set to . + + + is returned if the property is found. is returned in all other situations. + + @@ -57,7 +85,7 @@ - A nullable guid uniquely identifying the connection that the xommand is being executed on. + A nullable guid uniquely identifying the connection that the command is being executed on. diff --git a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs index 5dfbf8af3f..9f789d36fd 100644 --- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs @@ -308,13 +308,13 @@ public sealed partial class SqlBulkCopyColumnMapping { /// public SqlBulkCopyColumnMapping() { } - /// + /// public SqlBulkCopyColumnMapping(int sourceColumnOrdinal, int destinationOrdinal) { } - /// + /// public SqlBulkCopyColumnMapping(int sourceColumnOrdinal, string destinationColumn) { } - /// + /// public SqlBulkCopyColumnMapping(string sourceColumn, int destinationOrdinal) { } - /// + /// public SqlBulkCopyColumnMapping(string sourceColumn, string destinationColumn) { } /// public string DestinationColumn { get { throw null; } set { } } @@ -333,13 +333,13 @@ internal SqlBulkCopyColumnMappingCollection() { } public Microsoft.Data.SqlClient.SqlBulkCopyColumnMapping this[int index] { get { throw null; } } /// public Microsoft.Data.SqlClient.SqlBulkCopyColumnMapping Add(Microsoft.Data.SqlClient.SqlBulkCopyColumnMapping bulkCopyColumnMapping) { throw null; } - /// + /// public Microsoft.Data.SqlClient.SqlBulkCopyColumnMapping Add(int sourceColumnIndex, int destinationColumnIndex) { throw null; } - /// + /// public Microsoft.Data.SqlClient.SqlBulkCopyColumnMapping Add(int sourceColumnIndex, string destinationColumn) { throw null; } - /// + /// public Microsoft.Data.SqlClient.SqlBulkCopyColumnMapping Add(string sourceColumn, int destinationColumnIndex) { throw null; } - /// + /// public Microsoft.Data.SqlClient.SqlBulkCopyColumnMapping Add(string sourceColumn, string destinationColumn) { throw null; } /// public new void Clear() { } @@ -359,7 +359,7 @@ public void Remove(Microsoft.Data.SqlClient.SqlBulkCopyColumnMapping value) { } /// public sealed class SqlBulkCopyColumnOrderHint { - /// + /// public SqlBulkCopyColumnOrderHint(string column, SortOrder sortOrder) { } /// public string Column { get { throw null; } set { } }