如何根据另一个表值自动更新表数据? [英] How do I auto update table data based on another table value?

查看:357
本文介绍了如何根据另一个表值自动更新表数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Table1,它是使用表A和表B中的数据填充的.当前,一旦用户更改了表A的数据,就会运行查询以更新表A,然后另一个查询将更新表1.
如果表A有任何更改,如何使表1自动更新?

我尝试过的事情:

我读过有关使用触发器来执行此操作的信息,但是我不太确定这是否是正确的执行方式,或者我是否错了.

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.

推荐答案

<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;


这篇关于如何根据另一个表值自动更新表数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆