有時需要通過C#一次性插入或更新大量數據到SQL Server中,使用insert into/update這種方式就會變得異常緩慢,這個時候可以使用到表值參數來一次性插入或更新大量數據。需要注意,UpdateSale方法table參數的結構需要和表自定義類型結構、數據庫表結構一樣,比如下面的Type_SaleUpdate表自定義類型有id、Name、CreateDate三個字段,那么傳進來的table參數也要有這三個字段,總之table參數的結構要和表自定義類型、數據庫表一樣。下面是具體代碼:
1 public static void UpdateSale(DataTable table) 2 { 3 if (table.Rows.Count <= 0) 4 return; 5 List<string> sqlList = new List<string>() 6 { 7 "if exists(select * from sys.objects where name = 'DownLoad_SaleInsertProc') drop proc DownLoad_SaleInsertProc", //判斷存儲過程是否存在,存在即刪除 8 "if exists(select * from sys.types where name = 'Type_SaleInsert') drop type Type_SaleInsert", //判斷表自定義類型是否存在,存在即刪除 9 "if exists(select * from sys.objects where name = 'DownLoad_SaleUpdateProc') drop proc DownLoad_SaleUpdateProc", 10 "if exists(select * from sys.types where name = 'Type_SaleUpdate') drop type Type_SaleUpdate", 11 12 @"create type Type_SaleUpdate as table( //創建表自定義類型 13 Id uniqueidentifier not null, 14 Name nvarchar(20) not null, 15 CreateDate datetime )", 16 17 @"create proc DownLoad_SaleUpdateProc(@Table Type_SaleUpdate readonly) //創建存儲過程,使用表值參數更新表數據 18 as 19 begin 20 update Sale set 21 id=b.id,Name =b.Name,CreateDate =b.CreateDate from Sale a 22 left join @Tableb on b.id = a.id where b.id is not null 23 end;", 24 25 @"create type Type_SaleInsert as table( //創建表自定義類型 26 Id uniqueidentifier not null, 27 Name nvarchar(20) not null, 28 CreateDate datetime )", 29 30 @"create proc DownLoad_SaleInsertProc(@Table Type_SaleInsert readonly) //創建存儲過程,使用表值參數插入數據 31 as 32 begin 33 insert into Sale select distinct a.* from @Table a 34 where (select count(1) from Sale b where a.id = b.id) = 0 35 end;" 36 }; 37 SqlParameter[] sqlsUpdate = new SqlParameter[] {new SqlParameter("@Table", SqlDbType.Structured){ TypeName = "Type_SaleUpdate",Value = table}}; //設置表值參數的值,以及表值參數的數據類型 38 SqlParameter[] sqlsInsert = new SqlParameter[] {new SqlParameter("@Table", SqlDbType.Structured){ TypeName = "Type_SaleInsert",Value = table}}; 39 UserData.ExecuteNonQueryProc("", sqlList); //執行建表,創建存儲過程等SQL語句 40 UserData.ExecuteNonQueryProc("", "DownLoad_SaleUpdateProc", sqlsUpdate); //使用存儲過程更新數據 41 UserData.ExecuteNonQueryProc("", "DownLoad_SaleInsertProc", sqlsInsert); //使用存儲過程插入數據 42 }