有时需要通过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 }