SQL Server触发器:更新查询新旧数据

时间:2016-02-12 12:58:17

标签: sql sql-server triggers sql-update

我有两张桌子。一个人有员工信息。另一个我想根据这个员工表添加记录。

我想要发生的是每当对employee表进行薪水调整时(通过UDPATE查询),额外的表将添加一行,其中包含新的事件ID以及调整工资的金额(如果5个人的工资增加了1000英镑,那么这一行将调整为5000英镑)。

我已创建触发器,并在每次更新时添加行。然而它不做的只是带来额外的工资。我想不出怎么做。到目前为止我有这个代码;

Create trigger Salaryupdate
On TBL_Employees 
For update
As
    Insert TBL_audit (notes,Delta,AdjDate)
        Select 'Salary update', sum(salary), getdate()
        From TBL_Employees 

我知道sum位错了,因为我只想要改变工资值,而不是总和。

如何找到已更改行(或其他方法)的新值和旧值之间的差异?

我正在使用SQL Server 2008。

1 个答案:

答案 0 :(得分:3)

您应该在触发器中使用deletedinserted表。所以,我想:

Create trigger Salaryupdate
On TBL_Employees 
For update
As
    Insert TBL_audit(notes, Delta, AdjDate)
        Select 'Salary update',
               coalesce(newsalary, 0) - coalesce(oldsalary, 0),
               getdate()
        From (select sum(salary) as newsalary from inserted) i cross join
             (select sum(salary) as oldsalary from deleted) d;

此外,在SQL Server中,您可以将AdjDate设置为默认值getdate() - 这样,数据库会在您插入另一行时设置值。