我如何优化触发器

时间:2019-09-14 14:25:08

标签: sql sql-server

我之前检查了很多问题,但无法获得如何优化此触发器的方法


ALTER trigger [dbo].[Expample] 
on [dbo].[AdminUsers]
for update
as begin

declare @Id int
declare @new_val nvarchar(max)
declare @old_val nvarchar(max)

Declare @AuditString nvarchar(max)
  Select *
      into #TempTable
      from inserted

 While(Exists(Select Id from #TempTable))
      Begin
      Set @AuditString = ''

      Select Top 1 @Id = Id,@new_val = Fname
        from #TempTable

        Select @old_val = Fname
        from deleted where Id = @Id

        Set @AuditString = 'Id = ' + Cast(@Id as nvarchar(4)) + ' changed'

         if(@old_val <> @new_val)
                  Set @AuditString = @AuditString + ' NAME from ' + @old_val + ' to ' + @new_val

                   insert into [dbo].[tbl_audit] (Id,Auditdata) values(@Id,@AuditString)

            -- Delete the row from temp table, so we can move to the next row
            Delete from #TempTable where Id = @Id
end
end

我如何将此代码更改为

ALTER触发[dbo]。[示例] 在[dbo]上。[AdminUsers] 更新 一开始

声明@Id int 声明@new_val nvarchar(max) 声明@old_val nvarchar(max)

声明@AuditString nvarchar(max)  开始       设置@AuditString =''

  Select Top 1 @Id=inserted.Id,@new_val =inserted.Fname,@old_val = deleted.Fname from inserted join deleted on inserted.Id=deleted.Id 
 -- Select Top 1 @Id = Id,@new_val = Fname
 --   from #TempTable

    --Select @old_val = Fname
    --from deleted where Id = @Id

    Set @AuditString = 'Id = ' + Cast(@Id as nvarchar(4)) + ' changed'

     if(@old_val <> @new_val)
              Set @AuditString = @AuditString + ' NAME from ' + @old_val + ' to ' + @new_val

               insert into [dbo].[tbl_audit] (Id,Auditdata) values(@Id,@AuditString)

        -- Delete the row from temp table, so we can move to the next row

结束 结束

感谢帮助

1 个答案:

答案 0 :(得分:0)

我无法对其进行测试,但看来这是您要完成的工作:

ALTER trigger [dbo].[Expample]
on [dbo].[AdminUsers]
for update
as begin

    insert into [dbo].[tbl_audit] (Id, Auditdata)
    select t1.Id, 'Id = ' + Cast(t1.Id as nvarchar(4)) + ' changed NAME from ' + t2.Fname + ' to ' + t1.Fname
    from inserted t1
    join deleted t2 on t2.Id = t1.Id and t2.Fname != t1.Fname