SQL 批量插入数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL 批量插入数据相关的知识,希望对你有一定的参考价值。
参考技术A 循环插入:DECLARE @MyCounter INT
SET @MyCounter = 0 /*设置变量*/
WHILE (@MyCounter < 2) /*设置循环次数*/
BEGIN
WAITFOR DELAY '000:00:10' /*延迟时间10秒*/
INSERT INTO time_by_day
(time_id, the_date, the_year, month_of_year, quarter, day_of_month)
SELECT TOP 1 time_id + 1 AS time_id, the_date + 1 AS the_date, YEAR(the_date + 1)
AS the_year, MONTH(the_date + 1) AS month_of_year, fn QUARTER(the_date + 1)
AS quarter, DAY(the_date + 1) AS day_of_month
FROM time_by_day
ORDER BY time_id DESC
SET @MyCounter = @MyCounter + 1
END本回答被提问者采纳
SQL批量插入数据万级
1、每4000条插入一次
for (int i = 0; i < dt.Rows.Count; i++) { IsTBProductForStockInfo model = new IsTBProductForStockInfo(); model.SyncSkuCode = dt.Rows[i]["SyncSkuCode"].ToString(); model.SkuId = dt.Rows[i]["SkuId"].ToString(); info.Add(model); rowcount = rowcount + 1; tabIndex = tabIndex + 1; if (rowcount == pagesize) { if (listsize - tabIndex < 4000) { pagesize = listsize - tabIndex; } BatchAddNciicUserInfo(info) } } public static string BatchAddNciicUserInfo(List<IsTBProductForStockInfo> listData) { int i = 0; using (SqlConnection conn = new SqlConnection(ConnectionString)) { if (conn.State != ConnectionState.Open) { conn.Open(); } using (SqlTransaction tran = conn.BeginTransaction()) { try { using (SqlBulkCopy sqlDB = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tran)) { DataTable dtSource = new DataTable(); dtSource.Columns.Add("SkuId", typeof(int)); dtSource.Columns.Add("SyncSkuCode", typeof(string)); dtSource.Columns.Add("Spec", typeof(string)); dtSource.Columns.Add("OldQtyonhand", typeof(int)); dtSource.Columns.Add("NewQtyonhand", typeof(int)); dtSource.Columns.Add("Status", typeof(string)); dtSource.Columns.Add("Times", typeof(DateTime)); dtSource.Columns.Add("usersecretkey", typeof(string)); foreach (var item in listData) { DataRow dr = dtSource.NewRow(); dr["SkuId"] = item.SkuId; dr["SyncSkuCode"] = item.SyncSkuCode; dr["Spec"] = item.Spec; dr["OldQtyonhand"] = item.OldQtyonhand; dr["NewQtyonhand"] = item.NewQtyonhand; dr["Status"] = item.Status; dr["Times"] = DateTime.Now; dr["usersecretkey"] = item.usersecretkey; dtSource.Rows.Add(dr); i = i + 1; } sqlDB.BatchSize = 10000; sqlDB.BulkCopyTimeout = 60; sqlDB.DestinationTableName = string.Format("dbo.za_IsTBProductForStock"); sqlDB.ColumnMappings.Add("SkuId", "SkuId"); sqlDB.ColumnMappings.Add("SyncSkuCode", "SyncSkuCode"); sqlDB.ColumnMappings.Add("Spec", "Spec"); sqlDB.ColumnMappings.Add("OldQtyonhand", "OldQtyonhand"); sqlDB.ColumnMappings.Add("NewQtyonhand", "NewQtyonhand"); sqlDB.ColumnMappings.Add("Status", "Status"); sqlDB.ColumnMappings.Add("Times", "Times"); sqlDB.ColumnMappings.Add("usersecretkey", "usersecretkey"); sqlDB.WriteToServer(dtSource); } tran.Commit(); } catch (Exception ex) { tran.Rollback(); throw ex; } } } return "插入成功"; }
10000条数据用时25秒左右!!!!
以上是关于SQL 批量插入数据的主要内容,如果未能解决你的问题,请参考以下文章