在我們的一個(gè)(C#)應(yīng)用程序中,我們正在插入/更新一個(gè)大圖(100個(gè)插入和更新)。這被包裝在事務(wù)中,因?yàn)槿绻l(fā)生錯(cuò)誤,我需要整個(gè)回滾。我們正在使用Dapper執(zhí)行SQL語句。不幸的是,整個(gè)操作目前需要2到8秒。這是數(shù)據(jù)庫中核心表被鎖定的2到8秒,這導(dǎo)致其他應(yīng)用程序掛起或遭受鎖定。我確定插入到包含超過1.2億條記錄的表中的一項(xiàng)操作大部分時(shí)間都在占用,但是我不確定如何優(yōu)化此操作。大致而言,該表圖的設(shè)置如下:table A ( id int primary_key, name nvarchar)table B ( id int primary_key, a_id int foreign_key, # has an index name nvarchar)將數(shù)據(jù)插入時(shí),A我還需要將相應(yīng)的數(shù)據(jù)插入B。因此,我scope_identity()用來獲取記錄的ID,并在將記錄插入時(shí)使用它B。偽明智地如下所示:# open transaction# perform other table inserts## this is one of the slowest operationsfor item in list_a id_a = exec "insert into A (name) values (" + item.name + "); select scope_identity() as int" for bar in item.list_b exec "insert into B (id_a, name) values (" + id_a + ", " + bar.name + ")"## perform more operations# commit transaction谷歌搜索時(shí),解決方案之一是將其包裝在事務(wù)中。但是我不知道性能如何,因?yàn)樗呀?jīng)包裝在父事務(wù)中。它能解決問題嗎?通過使用插入記錄來提供第二種解決方案union all select...,但是不知道我是否可以scope_identity()在該調(diào)用中使用。我該如何改善這種情況?為了加快操作速度或防止其他應(yīng)用程序遭受這些鎖定,我還能做些其他事情嗎?
用scope_identity()用法執(zhí)行嵌套批量插入的最快方法?
慕娘9325324
2019-10-22 21:18:01