Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have Table1 which I populated using the data from Table A and Table B. Currently, once the user makes a change in either Table A's data, a query is run to update Table A and then another query will update Table1.
How do I make it so that Table1 will automatically update if there are any changes in Table A?

What I have tried:

I read about using triggers to do this but I'm not too sure whether this is the correct way of doing it or if I'm wrong. Any input will be appreciated.
Posted
Updated 30-Aug-18 23:36pm
Comments
Richard Deeming 31-Aug-18 11:14am    
Could you use a view instead of a table? That way, it would always be up-to-date.
Member 13968321 1-Sep-18 4:42am    
I've never used view before so it didn't cross my mind. Do I use it like a normal table? I'm assuming that I should make a view for Table1, if so, will a user be able to update the data from there? Or am I understanding it wrongly?
Richard Deeming 3-Sep-18 16:07pm    
You can query a view just like a regular table.

If you need to insert, update or delete records from the view, and it references data from more than one table, you'd need to add an INSTEAD OF trigger.

Using INSTEAD OF Triggers On Views[^]
Using INSTEAD OF triggers in SQL Server for DML operations[^]

1 solution

SQL
<pre>
--I hope this help full instead of Triggers offcourse Triggers is performance issue.
--I Have created sample table 
Declare @tableA table(Id int identity(1,1),Name Varchar(400));
Declare @Temp   table(Id INT,Name Varchar(400));
Declare @table1 table(Id int identity(1,1),Name Varchar(400));

---inserted same records in both tables @tableA and @table1

INSERT INTO @tableA VALUES('harish'),('santosh'),('sai'),('satish');

INSERT INTO @table1 VALUES('harish'),('santosh'),('sai'),('satish');

SELECT * FROM @tableA  WHERE id=2;
--updates name with 'NigamLucky' instead of 'santosh' in table @tableA
UPDATE @tableA SET Name='NigamLucky' OUTPUT INSERTED.* INTO @Temp  WHERE id=2;
--updates new values are inserted in @temp 
if(@@ROWCOUNT<>0)
BEGIN --@temp is joined and updated with @table1
UPDATE t1 set t1.name=t.Name from @table1 AS t1 INNER JOIN @Temp  AS t ON(t1.id=t.id)
END;
SELECT * FROM @tableA  WHERE id=2;
SELECT * FROM @table1  WHERE id=2;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900