C#中使用SQL的BULK语句,进行大数据量操作
下面是C#中如何使用SQL的BULK类语句,对大量数据执行操作。
下面主要是将另外一张表的内容移植到新的临时表中,以便后面操作。
string connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand("CREATE TABLE #helloworld([Serial_No] [nvarchar](100),[Product_Code] [nvarchar](100)) SELECT COUNT(*) FROM " + "#helloworld", connection);
long countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// 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 = "#helloworld";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(dt);
SqlCommand commandRowCountAll = new SqlCommand("select h.Serial_No,p.Product_Code,p.origin,p.warehouse_code,h.Product_Code AS PRODUCT_CODE_ERROR from #helloworld h left join TB_PRODUCTINFORMATION p on h.Serial_No = p.SERIAL_NO and p.PRODUCT_CODE like h.Product_Code+'%'", connection);
DataTable datatable = new DataTable();
new SqlDataAdapter(commandRowCountAll).Fill(datatable);
return datatable;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
浙公网安备 33010602011771号