Mettre à jour le triggersur de la boucle d'instruction select

J'ai le tableau suivant:

 SystemList

 Valeur du système1 Valeur2 Valeur3 Valeur4 Total

 Système1 10 30 40
 System2 20
 System3 10 30
 System4 30 40

J'ai ce qui suit dans un triggersur qui fonctionne bien, mais je veux parcourir tous les systèmes et mettre à jour le total de chaque ligne sans avoir à le faire en réalité 92 fois. Existe-t-il un moyen d'effectuer une search des systèmes et de totaliser les valeurs de cette ligne à chaque insertion ou mise à jour?

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' 

Mon triggersur actuel est:

 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 

Vous n'êtes pas obligé de spécifier chaque valeur dans une requête distincte comme vous le faites. Ce serait plus simple.

 UPDATE dbo.SystemList SET Total = COALESCE(Value1, 0) + COALESCE(Value2, 0) + COALESCE(Value3, 0) + COALESCE(Value4, 0)) 

Ou vous pouvez le faire encore plus facilement. Utilisez plutôt une colonne calculée dans votre table et vous n'avez même pas besoin d'un sortinggger.

 Alter TABLE SystemList Add Total as isnull(Value1, 0) + isnull(Value2, 0) + isnull(Value3, 0) + isnull(Value4, 0) 

https://msdn.microsoft.com/en-us/library/ms188300.aspx