批量删除死锁,需要更好的性能

时间:2017-03-16 17:38:40

标签: sql sql-server transactions database-deadlocks

我正在对一组ID进行批量删除,作为发送到以逗号分隔的存储过程的字符串。我有一个函数将它们分成一个表,以便我可以与它们进行比较。即使我有SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;,我有时会对此SP造成僵局。是否有更好的方法来进行批量删除,然后使用SP来提高性能并且没有死锁?

    DELETE FROM Game
            WHERE Id IN (
                SELECT g.Id 
                FROM Game g
                INNER JOIN [EventGame] eg ON g.Id = eg.Id
                INNER JOIN MemberEvent me ON me.EventId = eg.EventId
                WHERE 
                    eg.EventId = @EventId AND
                    g.Id IN (SELECT * FROM dbo.Split(@DeletedGameIds, ',')) AND
                    (g.[Type] = 1 OR g.[Type] IS NULL) AND 
                    me.MemberId = @MemberId
)

1 个答案:

答案 0 :(得分:0)

更好的删除方法是识别要删除的id列表,然后只通过i​​d进行聚簇索引删除。

CREATE Table #temp (Id Int)

Insert into #temp (Id) 
SELECT Id FROM Game
            WHERE Id IN (
                SELECT g.Id 
                FROM Game g
                INNER JOIN [EventGame] eg ON g.Id = eg.Id
                INNER JOIN MemberEvent me ON me.EventId = eg.EventId
                WHERE 
                    eg.EventId = @EventId AND
                    g.Id IN (SELECT * FROM dbo.Split(@DeletedGameIds, ',')) AND
                    (g.[Type] = 1 OR g.[Type] IS NULL) AND 
                    me.MemberId = @MemberId
)

--you can do this delete in looping with batch size of 50000 records and use checkpoint
DELETE G
FROM Game G
Inner Join #temp t
ON G.ID = t.Id
--checkpoint