我有下表:
SystemList System Value1 Value2 Value3 Value4 Total System1 10 30 40 System2 20 System3 10 30 System4 30 40
我在触发器中有以下工作正常但我想迭代每个系统并更新每行的总计而不必实际执行92次。有插入或更新时,是否有办法查找系统并累计该行中的值?
Use Database
UPDATE dbo.SystemList
SET Total = (SELECT (COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0)) AS Total
FROM dbo.SystemList where System = 'System1') Where System = 'System1'
UPDATE dbo.SystemList
SET Total = (SELECT (COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0)) AS Total
FROM dbo.SystemList where System = 'System2') Where System = 'System2'
UPDATE dbo.SystemList
SET Total = (SELECT (COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0)) AS Total
FROM dbo.SystemList where System = 'System3') Where System = 'System3'
UPDATE dbo.SystemList
SET Total = (SELECT (COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0)) AS Total
FROM dbo.SystemList where System = 'System4') Where System = 'System4'
我的实际触发器是:
USE [Database]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[Total]
ON [dbo].[SystemList]
AFTER INSERT,UPDATE
AS
Begin
UPDATE dbo.SystemList
SET Total = (SELECT (COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0)) AS Total
FROM dbo.SystemList where System = 'System1') Where System = 'System1'
UPDATE dbo.SystemList
SET Total = (SELECT (COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0)) AS Total
FROM dbo.SystemList where System = 'System2') Where System = 'System2'
UPDATE dbo.SystemList
SET Total = (SELECT (COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0)) AS Total
FROM dbo.SystemList where System = 'System3') Where System = 'System3'
UPDATE dbo.SystemList
SET Total = (SELECT (COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0)) AS Total
FROM dbo.SystemList where System = 'System4') Where System = 'System4'
End
答案 0 :(得分:3)
您不必在单独的查询中指定每个值,就像您正在做的那样。这会更简单。
v
或者你可以更轻松地做到这一点。改为使用表格中的计算列,您甚至不需要触发器。
UPDATE dbo.SystemList SET Total = COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0))