我正在做一个循环插入,如下所示(方法A),似乎每个循环调用数据库不是一个好主意。我发现一种替代方法是在我的SProc中循环逗号分隔的字符串,而不是执行插入操作,以便只有一个条目进入数据库。在性能方面会有什么重大改进? :SQL Server +循环插入性能
方法A:
foreach (DataRow row in dt.Rows)
{
userBll = new UserBLL();
UserId = (Guid)row["UserId"];
// Call userBll method to insert into SQL Server with UserId as one of the parameter.
}
方法B:
string UserIds = "Tom, Jerry, 007"; // Assuming we already concatenate the strings. So no loops this time here.
userBll = new UserBLL();
// Call userBll method to insert into SQL Server with 'UserIds' as parameter.
方法B SPROC /执行在SPROC环插入件。
if right(rtrim(@UserIds), 1) <> ','
SELECT @string = @UserIds + ','
SELECT @pos = patindex('%,%' , @UserIds)
while @pos <> 0
begin
SELECT @piece = left(@v, (@pos-1))
-- Perform the insert here
SELECT @UserIds = stuff(@string, 1, @pos, '')
SELECT @pos = patindex('%,%' , @UserIds)
end
我假设SQL Server - 如果是这样,哪个版本? – Bridge 2013-02-26 15:00:16
这是SQL Server 2008R2 – k80sg 2013-02-26 15:00:44
您也可以通过'方法B + XML'将CSV值作为行返回,而不循环,然后执行INSERT INTO TABLE SELECT * FROM ... – 2013-02-26 15:13:57