在单个表上插入导致死锁

时间:2010-10-14 11:26:02

标签: c# sql-server deadlock spring.net

我正在使用SQLServer 2005并设计了一个运行insert sql的DAO,如下所示:

INSERT INTO eventsources (recevied_event_time_stamp, recevied_event_curve_name, recevied_event_curve_value, recevied_event_quote_date, total_time_for_event_processing, number_of_published_events{0}, triggered_curve, recevied_event_day)
但是,系统在运行一段时间后会抛出死锁异常,这对我来说似乎不可能,我认为只有在以相反的顺序使用多个资源时才会发生死锁。

插入是多线程的,这可能是个问题吗?但我使用的是Spring.Net的AdoTemplate,它宣布是线程安全的。

我在eventsources表上创建了一个触发器

CREATE TRIGGER TRIGGER_EVENTSOURCES
ON eventsources
FOR INSERT
AS
DECLARE @newlyInertedFormulaName VARCHAR(100)
DECLARE @error_message varchar(10)
DECLARE @last_calculated_date datetime
DECLARE @timeframe datetime
DECLARE @publishedEvent int

SELECT @publishedEvent = (SELECT number_of_published_events FROM Inserted)
SELECT @newlyInertedFormulaName = (SELECT triggered_curve FROM Inserted)
SELECT @error_message = (SELECT error_message FROM Inserted)
SELECT @last_calculated_date = (SELECT recevied_event_time_stamp FROM Inserted)

if @publishedEvent > 0
BEGIN
    update formulaversions set last_calculated_date = @last_calculated_date where 

formulaname = @newlyInertedFormulaNam
e and lifecycle = 3;
END

if @error_message is not NULL
        BEGIN
                update formulaversions set status = 2 where formulaname = @newlyInertedFormulaName and lifecycle = 3;
        END
ELSE
        update formulaversions set status = 1 where formulaname = @newlyInertedFormulaName and lifecycle = 3 and (status <>
 2 or status is null);       

GO

使用此触发器有什么问题吗?

任何意见将不胜感激。

1 个答案:

答案 0 :(得分:1)

根本原因是触发器中的三个更新语句,它可能以不同的顺序锁定同一行,这会导致问题,SQL Server Profiler非常有助于弄清楚这一点。

http://msdn.microsoft.com/en-us/library/ms190465.aspx