SQL Server 批量插入數據的兩種方法

原文:http://blog.csdn.net/tjvictor/article/details/4360030sql

 在SQL Server 中插入一條數據使用Insert語句,可是若是想要批量插入一堆數據的話,循環使用Insert不只效率低,並且會致使SQL一系統性能問題。下面介紹SQL Server支持的兩種批量數據插入方法:Bulk和表值參數(Table-Valued Parameters)。數據庫

運行下面的腳本,創建測試數據庫和表值參數。緩存

 

[c-sharp]  view plain copy
 
  1. --Create DataBase  
  2. create database BulkTestDB;  
  3. go  
  4. use BulkTestDB;  
  5. go  
  6. --Create Table  
  7. Create table BulkTestTable(  
  8. Id int primary key,  
  9. UserName nvarchar(32),  
  10. Pwd varchar(16))  
  11. go  
  12. --Create Table Valued  
  13. CREATE TYPE BulkUdt AS TABLE  
  14.   (Id int,  
  15.    UserName nvarchar(32),  
  16.    Pwd varchar(16))  

 

 

下面咱們使用最簡單的Insert語句來插入100萬條數據,代碼以下:性能

 

[c-sharp]  view plain copy
 
  1. Stopwatch sw = new Stopwatch();  
  2.   
  3. SqlConnection sqlConn = new SqlConnection(  
  4.     ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);//鏈接數據庫  
  5.   
  6. SqlCommand sqlComm = new SqlCommand();  
  7. sqlComm.CommandText = string.Format("insert into BulkTestTable(Id,UserName,Pwd)values(@p0,@p1,@p2)");//參數化SQL  
  8. sqlComm.Parameters.Add("@p0", SqlDbType.Int);  
  9. sqlComm.Parameters.Add("@p1", SqlDbType.NVarChar);  
  10. sqlComm.Parameters.Add("@p2", SqlDbType.VarChar);  
  11. sqlComm.CommandType = CommandType.Text;  
  12. sqlComm.Connection = sqlConn;  
  13. sqlConn.Open();  
  14. try  
  15. {  
  16.     //循環插入100萬條數據,每次插入10萬條,插入10次。  
  17.     for (int multiply = 0; multiply < 10; multiply++)  
  18.     {  
  19.         for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++)  
  20.         {  
  21.   
  22.             sqlComm.Parameters["@p0"].Value = count;  
  23.             sqlComm.Parameters["@p1"].Value = string.Format("User-{0}", count * multiply);  
  24.             sqlComm.Parameters["@p2"].Value = string.Format("Pwd-{0}", count * multiply);  
  25.             sw.Start();  
  26.             sqlComm.ExecuteNonQuery();  
  27.             sw.Stop();  
  28.         }  
  29.         //每插入10萬條數據後,顯示這次插入所用時間  
  30.         Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));  
  31.     }  
  32. }  
  33. catch (Exception ex)  
  34. {  
  35.     throw ex;  
  36. }  
  37. finally  
  38. {  
  39.     sqlConn.Close();  
  40. }  
  41.   
  42. Console.ReadLine();  

 

耗時圖以下:測試

使用Insert語句插入10萬數據的耗時圖

因爲運行過慢,才插入10萬條就耗時72390 milliseconds,因此我就手動強行中止了。spa

 

下面看一下使用Bulk插入的狀況:.net

bulk方法主要思想是經過在客戶端把數據都緩存在Table中,而後利用SqlBulkCopy一次性把Table中的數據插入到數據庫pwa

代碼以下:orm

 

[c-sharp]  view plain copy
 
  1. public static void BulkToDB(DataTable dt)  
  2. {  
  3.     SqlConnection sqlConn = new SqlConnection(  
  4.         ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);  
  5.     SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn);  
  6.     bulkCopy.DestinationTableName = "BulkTestTable";  
  7.     bulkCopy.BatchSize = dt.Rows.Count;  
  8.   
  9.     try  
  10.     {  
  11.         sqlConn.Open();  
  12.     if (dt != null && dt.Rows.Count != 0)  
  13.         bulkCopy.WriteToServer(dt);  
  14.     }  
  15.     catch (Exception ex)  
  16.     {  
  17.         throw ex;  
  18.     }  
  19.     finally  
  20.     {  
  21.         sqlConn.Close();  
  22.         if (bulkCopy != null)  
  23.             bulkCopy.Close();  
  24.     }  
  25. }  
  26.   
  27. public static DataTable GetTableSchema()  
  28. {  
  29.     DataTable dt = new DataTable();  
  30.     dt.Columns.AddRange(new DataColumn[]{  
  31.         new DataColumn("Id",typeof(int)),  
  32.         new DataColumn("UserName",typeof(string)),  
  33.     new DataColumn("Pwd",typeof(string))});  
  34.   
  35.     return dt;  
  36. }  
  37.   
  38. static void Main(string[] args)  
  39. {  
  40.     Stopwatch sw = new Stopwatch();  
  41.     for (int multiply = 0; multiply < 10; multiply++)  
  42.     {  
  43.         DataTable dt = Bulk.GetTableSchema();  
  44.         for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++)  
  45.         {  
  46.             DataRow r = dt.NewRow();  
  47.             r[0] = count;  
  48.             r[1] = string.Format("User-{0}", count * multiply);  
  49.             r[2] = string.Format("Pwd-{0}", count * multiply);  
  50.             dt.Rows.Add(r);  
  51.         }  
  52.         sw.Start();  
  53.         Bulk.BulkToDB(dt);  
  54.         sw.Stop();  
  55.         Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));  
  56.     }  
  57.   
  58.     Console.ReadLine();  
  59. }  

 

耗時圖以下:blog

使用Bulk插入100萬數據的耗時圖

可見,使用Bulk後,效率和性能明顯上升。使用Insert插入10萬數據耗時72390,而如今使用Bulk插入100萬數據才耗時17583。

 

最後再看看使用表值參數的效率,會另你大爲驚訝的。

 

表值參數是SQL Server 2008新特性,簡稱TVPs。對於表值參數不熟悉的朋友,能夠參考最新的book online,我也會另外寫一篇關於表值參數的博客,不過這次不對錶值參數的概念作過多的介紹。言歸正傳,看代碼:

 

[c-sharp]  view plain copy
 
  1. public static void TableValuedToDB(DataTable dt)  
  2. {  
  3.     SqlConnection sqlConn = new SqlConnection(  
  4.       ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);  
  5.     const string TSqlStatement =  
  6.      "insert into BulkTestTable (Id,UserName,Pwd)" +  
  7.      " SELECT nc.Id, nc.UserName,nc.Pwd" +  
  8.      " FROM @NewBulkTestTvp AS nc";  
  9.     SqlCommand cmd = new SqlCommand(TSqlStatement, sqlConn);  
  10.     SqlParameter catParam = cmd.Parameters.AddWithValue("@NewBulkTestTvp", dt);  
  11.     catParam.SqlDbType = SqlDbType.Structured;  
  12.     //表值參數的名字叫BulkUdt,在上面的創建測試環境的SQL中有。  
  13.     catParam.TypeName = "dbo.BulkUdt";  
  14.     try  
  15.     {  
  16.       sqlConn.Open();  
  17.       if (dt != null && dt.Rows.Count != 0)  
  18.       {  
  19.           cmd.ExecuteNonQuery();  
  20.       }  
  21.     }  
  22.     catch (Exception ex)  
  23.     {  
  24.       throw ex;  
  25.     }  
  26.     finally  
  27.     {  
  28.       sqlConn.Close();  
  29.     }  
  30. }  
  31.   
  32. public static DataTable GetTableSchema()  
  33. {  
  34.     DataTable dt = new DataTable();  
  35.     dt.Columns.AddRange(new DataColumn[]{  
  36.       new DataColumn("Id",typeof(int)),  
  37.       new DataColumn("UserName",typeof(string)),  
  38.       new DataColumn("Pwd",typeof(string))});  
  39.   
  40.     return dt;  
  41. }  
  42.   
  43. static void Main(string[] args)  
  44. {  
  45.     Stopwatch sw = new Stopwatch();  
  46.     for (int multiply = 0; multiply < 10; multiply++)  
  47.     {  
  48.         DataTable dt = TableValued.GetTableSchema();  
  49.         for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++)  
  50.         {          
  51.             DataRow r = dt.NewRow();  
  52.             r[0] = count;  
  53.             r[1] = string.Format("User-{0}", count * multiply);  
  54.             r[2] = string.Format("Pwd-{0}", count * multiply);  
  55.             dt.Rows.Add(r);  
  56.         }  
  57.         sw.Start();  
  58.         TableValued.TableValuedToDB(dt);  
  59.         sw.Stop();  
  60.         Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));  
  61.     }  
  62.   
  63.     Console.ReadLine();  
  64. }  

 

耗時圖以下:

使用表值參數插入100萬數據的耗時圖

比Bulk還快5秒。

相關文章
相關標籤/搜索