SQL Server:在其他表插入或更新记录后触发表的更新列

时间:2017-03-26 06:08:34

标签: sql-server triggers sql-update sql-insert

我有2个表,ShareButtonSharePage

ShareButton表:

+----+---------------+---------------+
| ID | Name          | TotalShare    |
+----+---------------+---------------+
|  1 | Facebook      |      0        |
|  2 | Twitter       |      0        |
+----+---------------+---------------+

SharePage表:

+----+--------------------+-------+---------------+
| ID |        URL         | Share | ShareButtonID |
+----+--------------------+-------+---------------+
| 1  | www.abc.xyz/page1  |    3  |      1        |
| 2  | www.abc.xyz/page1  |   14  |      2        |
| 3  | www.abc.xyz/page2  |    6  |      1        |
| 4  | www.abc.xyz/page2  |   10  |      2        |
+----+--------------------+-------+---------------+

SharePage表格中插入或更新记录后,TotalShare的{​​{1}}列已更新

ShareButton

感谢阅读!

1 个答案:

答案 0 :(得分:0)

让我通过说我同意Mureinik开始我的回答。除非您通过查询使用简单的组获得共享总和的性能非常糟糕,否则我不建议将该总和保存在ShareButton表中。

如果你真的想要一个触发器来计算它,我想最简单的方法就是:

CREATE TRIGGER trSharePage_Changed ON SharePage 
FOR UPDATE, INSERT, DELETE
AS

UPDATE buttons
SET TotalShare = SumOfShares
FROM ShareButton buttons
INNER JOIN 
(
    SELECT ShareButtonID, SUM(Share) As SumOfShares
    FROM SharePage 
    GROUP BY ShareButtonID
) pages ON buttons.ID = pages.ShareButtonID

请注意,在表SharePage上的任何insert,update或delete语句完成后,将触发此触发器。由于它是一个后触发器,因此您根本不需要处理插入和删除的表格。