用于记录历史记录的数据库触发器似乎会导致死锁异常

本文关键字:记录 死锁 异常 历史 数据库 触发器 用于 | 更新日期: 2023-09-27 17:54:10

当我调用我的存储过程来更新/插入到我的Configuration表中时,我在c#代码中得到死锁异常。

SP_Update_Configuration存储过程将插入一条新记录或更新一条现有记录。

设置触发器是为了在历史表中保存以前记录的历史记录。如果Configuration表有更新或插入,那么它应该将该记录添加到Configuration_History表中。

我相信是触发器导致了死锁?在添加触发器....之前,我没有遇到任何问题什么好主意吗?

我使用的是SQL Server 2012 Express.

下面是我的SQL示例:
CREATE PROCEDURE SP_Update_Configuration
( 
--Input variables
) 
AS
BEGIN TRANSACTION
DECLARE @RetCode INT
DECLARE @RowCnt INT
    --Standard Update Logic
SELECT @RowCnt = @@ROWCOUNT
IF @@ERROR <> 0
   BEGIN
    ROLLBACK TRAN
    SET @RetCode = 5
    RETURN @RetCode
   END
IF @RowCnt = 0
    BEGIN
        --Standard Insert Logic
    END
IF @@ERROR <> 0
   BEGIN
    ROLLBACK TRAN
    SET @RetCode = 5
    RETURN @RetCode
   END
COMMIT TRANSACTION
GO
create trigger dbo.Configuration_Log_Insert 
on dbo.Configuration
  for insert
as
  set nocount on
  insert into Configuration_History
    select *
      from Configuration
go
exec sp_settriggerorder @triggername = 'Configuration_Log_Insert', @order = 'last', @stmttype = 'insert'  
create trigger dbo.Configuration_Log_Update 
on dbo.Configuration
  for update
as
  set nocount on
  insert into Configuration_History
    select *
      from Configuration
go
exec sp_settriggerorder @triggername = 'Configuration_Log_Update', @order = 'last', @stmttype = 'update'

用于记录历史记录的数据库触发器似乎会导致死锁异常

SELECT @RowCnt = @@ROWCOUNT
IF @@ERROR <> 0

这里有问题,因为@@ERROR

的错误代码
SELECT @RowCnt = @@ROWCOUNT

你可以这样做:

SELECT @RowCnt = @@ROWCOUNT, @error = @@ERROR
IF @error <> 0

在触发器中有

  insert into Configuration_History
    select *
      from Configuration

但必须是

  insert into Configuration_History
    select *
      from inserted