我正在做一個循環插入,如下所示(方法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