我想知道是否有批量更新的方法?我正在使用ms sql server 2005。
我看到了sqlDataAdaptor,但似乎必须先用它选择语句,然后填充一些数据集并对数据集进行更改。
现在我正在使用linq to sql进行选择,所以我想尝试保持这种方式。但是,大规模更新太慢了。那么,有什么方法可以保留我的linq to sql(用于选择部分),但使用不同的东西进行大规模更新吗?
谢谢
编辑
我对这种暂存表的方式很感兴趣,但我不确定如何做以及如何更快,因为我不理解更新部分的工作原理。
那么,有人能向我展示这将如何运作以及如何处理并发连接吗?
编辑2
这是我最近尝试使用xml进行大规模更新的尝试,但它使用了太多资源,而我的共享主机不允许它通过。所以我需要一种不同的方式,因此我现在正在研究暂存表。
我看到了sqlDataAdaptor,但似乎必须先用它选择语句,然后填充一些数据集并对数据集进行更改。
现在我正在使用linq to sql进行选择,所以我想尝试保持这种方式。但是,大规模更新太慢了。那么,有什么方法可以保留我的linq to sql(用于选择部分),但使用不同的东西进行大规模更新吗?
谢谢
编辑
我对这种暂存表的方式很感兴趣,但我不确定如何做以及如何更快,因为我不理解更新部分的工作原理。
那么,有人能向我展示这将如何运作以及如何处理并发连接吗?
编辑2
这是我最近尝试使用xml进行大规模更新的尝试,但它使用了太多资源,而我的共享主机不允许它通过。所以我需要一种不同的方式,因此我现在正在研究暂存表。
using (TestDataContext db = new TestDataContext())
{
UserTable[] testRecords = new UserTable[2];
for (int count = 0; count < 2; count++)
{
UserTable testRecord = new UserTable();
if (count == 1)
{
testRecord.CreateDate = new DateTime(2050, 5, 10);
testRecord.AnotherField = true;
}
else
{
testRecord.CreateDate = new DateTime(2015, 5, 10);
testRecord.AnotherField = false;
}
testRecords[count] = testRecord;
}
StringBuilder sBuilder = new StringBuilder();
System.IO.StringWriter sWriter = new System.IO.StringWriter(sBuilder);
XmlSerializer serializer = new XmlSerializer(typeof(UserTable[]));
serializer.Serialize(sWriter, testRecords);
using (SqlConnection con = new SqlConnection(connectionString))
{
string sprocName = "spTEST_UpdateTEST_TEST";
using (SqlCommand cmd = new SqlCommand(sprocName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter param1 = new SqlParameter("@UpdatedProdData", SqlDbType.VarChar, int.MaxValue);
param1.Value = sBuilder.Remove(0, 41).ToString();
cmd.Parameters.Add(param1);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
}
}
}
@Fredrik Johansson,我不确定你的建议是否可行。在我看来,你似乎希望我为每个记录制作更新语句。但我不能这样做,因为我需要更新1到50,000多条记录,而且在那时之前我不会知道具体数量。
编辑3
所以现在我的存储过程是这样的。我认为它应该能够处理并发连接,但我想确保一下。
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_MassUpdate]
@BatchNumber uniqueidentifier
AS
BEGIN
update Product
set ProductQty = 50
from Product prod
join StagingTbl stage on prod.ProductId = stage.ProductId
where stage.BatchNumber = @BatchNumber
DELETE FROM StagingTbl
WHERE BatchNumber = @BatchNumber
END