0

I have data streaming from an external program to TABLE1 in my SQL Server database. Let's say TABLE1 consists of columns data1 and data2. How do I update to another table (TABLE2) when a value changes in TABLE1?

For the sake of an example, let's say a value in the data1 column changes.

Note: I wrote a trigger that works, but this is only on the basis of a manual update. I can't figure out how to automate this, meaning the trigger would compare new and old values from the table on its own and then perform the update if a value is different.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Nia
  • 11
  • 2
  • Does this answer your question? [Trigger to fire only if a condition is met in SQL Server](https://stackoverflow.com/questions/280904/trigger-to-fire-only-if-a-condition-is-met-in-sql-server) – Preben Huybrechts Jul 21 '20 at 19:43

1 Answers1

0

Something like below would work,

CREATE TRIGGER after_update_table1
AFTER UPDATE ON table1 
FOR EACH ROW 
BEGIN 
     IF OLD.val1<> new.val1 THEN
         /**
            -- do operations on table2
        **/ 
     END IF;
END;

-- if val1 allows null we need to check by adding more conditions to the if clause like,

IF((OLD.val1 IS NULL AND NEW.val1 IS NOT NULL) OR (OLD.val1 IS NOT NULL AND NEW.val1 IS NULL) OR (OLD.val1<>NEW.val1)) THEN

/**
-- operations on table2
**/
END IF;
Sujitmohanty30
  • 3,256
  • 2
  • 5
  • 23