Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Evitare i cursori per aggiornare molti record utilizzando un trigger

Sì. Puoi farlo con un singolo UPDATE - FROM dichiarazione dopo il tuo BULK INSERT :

UPDATE t3 SET initialValue = t.mySum
FROM test3 t3
CROSS APPLY (SELECT SUM(
       CASE t3.v1 WHEN 'M170_2' THEN CASE d.M170_2 
             WHEN 1 THEN 1 
             WHEN 2 THEN .75 
             WHEN 3 THEN .25 
             WHEN 4 THEN .1 
       ELSE 1 END END * 
       CASE t3.v1 WHEN 'M170_3' THEN CASE d.M170_3 
             WHEN 1 THEN 1 
             WHEN 2 THEN .75 
             WHEN 3 THEN .25 
             WHEN 4 THEN .1 
       ELSE 1 END END * 
       CASE t3.v1 WHEN 'M170_4' THEN CASE d.M170_4 
             WHEN 1 THEN 1 
             WHEN 2 THEN .75 
             WHEN 3 THEN .25 
             WHEN 4 THEN .1 
       ELSE 1 END END * 
       d.RESP_WEIGHT / 4898.947426) as mySum 
       FROM my_data_db d WHERE d.combo = t3.combo) t
WHERE t3.v1 IS NOT NULL OR t3.v2 IS NOT NULL OR t3.v3 IS NOT NULL

Per farlo dal tuo trigger, hai bisogno di una piccola modifica:

UPDATE t3 SET initialValue = t.mySum
FROM test3 t3
-- Here's the change
INNER JOIN inserted i ON i.RowID = t3.RowID
CROSS APPLY (SELECT SUM(
       CASE t3.v1 WHEN 'M170_2' THEN CASE d.M170_2 
             WHEN 1 THEN 1 
             WHEN 2 THEN .75 
             WHEN 3 THEN .25 
             WHEN 4 THEN .1 
       ELSE 1 END END * 
       CASE t3.v1 WHEN 'M170_3' THEN CASE d.M170_3 
             WHEN 1 THEN 1 
             WHEN 2 THEN .75 
             WHEN 3 THEN .25 
             WHEN 4 THEN .1 
       ELSE 1 END END * 
       CASE t3.v1 WHEN 'M170_4' THEN CASE d.M170_4 
             WHEN 1 THEN 1 
             WHEN 2 THEN .75 
             WHEN 3 THEN .25 
             WHEN 4 THEN .1 
       ELSE 1 END END * 
       d.RESP_WEIGHT / 4898.947426) as mySum 
       FROM my_data_db d WHERE d.combo = t3.combo) t
WHERE t3.v1 IS NOT NULL OR t3.v2 IS NOT NULL OR t3.v3 IS NOT NULL