T-SQL - 创建一个触发器,用过去90天内类似记录的平均值更新更新记录的平均时间?

时间:2015-08-17 13:25:58

标签: sql sql-server triggers sql-update

我正在尝试创建一个触发器,在调用时,将使用过去90天内的平均值更新最近更新的记录的RollingAvgTime列。

系统信息: SQL Server

表:

  • BatchLog

相关专栏:

  • ElapsedTime(计算值,平均值)
  • RollingAvgTime - 需要触发器
  • 滚动StdDev - 需要一个触发器
  • DifferenceFromAvg - 需要一个触发器

本质上,我试图更新最后三列(以前为空)以在存储过程更新记录时获得相关信息。

我非常乐意提供更多详情!提前致谢!

编辑:这是我现在使用的代码,它确实编译,但不正确。

CREATE TRIGGER TR_BatchLog_Update
ON dbo.BatchLog
AFTER UPDATE AS
BEGIN
SET NOCOUNT ON;

DECLARE @BatchLogNId INT
SELECT
  @BatchLogNId = INSERTED.BatchLogNId
FROM
  INSERTED
INNER JOIN
  DELETED
    ON INSERTED.BatchLogNId = DELETED.BatchLogNId
    -- It's an update if the record is in BOTH inserted AND deleted

UPDATE BatchLog
SET RollingAvgTime = (
 SELECT AVG(ElapsedTime)
 FROM BatchLog
 WHERE BatchLogNId = @BatchLogNId
 AND EndTime <= DATEADD(MONTH, -3, GETDATE())
)
END
GO

FINAL:

工作代码!

Use LogilityPHAdmin
GO
DROP TRIGGER TR_BatchLog_Update
GO
CREATE TRIGGER TR_BatchLog_Update
ON dbo.BatchLog
AFTER UPDATE AS
BEGIN
SET NOCOUNT ON;

UPDATE b
SET RollingAvgTime = (
 SELECT AVG(ElapsedTime)
 FROM BatchLog b2
 WHERE b2.EndTime > DATEADD(MONTH, -3, GETDATE())
 AND b2.DivCd = b.DivCd
 AND b2.ProgramName = b.ProgramName
 AND b2.Successful = 1
)
FROM BatchLog b
INNER JOIN inserted I
  ON b.BatchLogNId=i.BatchLogNId


UPDATE b
SET RollingStdDev = (
 SELECT STDEV(ElapsedTime)
 FROM BatchLog b2
 WHERE b2.EndTime > DATEADD(MONTH, -3, GETDATE())
 AND b2.DivCd = b.DivCd
 AND b2.ProgramName = b.ProgramName
 AND b2.Successful = 1
)
FROM BatchLog b
INNER JOIN inserted I
  ON b.BatchLogNId=i.BatchLogNId


UPDATE b
 SET DifferenceFromAvg = (b.RollingAvgTime - b.ElapsedTime)
 FROM BatchLog b
 INNER JOIN inserted I
 ON b.BatchLogNId=i.BatchLogNId

END
GO

1 个答案:

答案 0 :(得分:1)

试试这个。注意UPDATE如何连接到插入的表,以便它将处理多个插入,而不是使用变量。

CREATE TRIGGER TR_BatchLog_Update
ON dbo.BatchLog
AFTER UPDATE AS
BEGIN
SET NOCOUNT ON;

UPDATE b
SET RollingAvgTime = (
 SELECT AVG(DATEDIFF(minute,0,ElapsedTime))
 FROM BatchLog b2
 WHERE b2.BatchLogNId = b.BatchLogNId
 AND b2.EndTime <= DATEADD(MONTH, -3, GETDATE())
)
FROM BatchLog b
INNER JOIN inserted I
  ON b.BatchLogNId=i.BatchLogNId

END
GO