【问题标题】:SQL Server : trigger update column of table after other table insert or update a recordSQL Server:在其他表插入或更新记录后触发表的更新列
【发布时间】:2017-03-26 06:08:34
【问题描述】:

我有 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表中插入或更新一条记录后,ShareButtonTotalShare列被更新

update ShareButton 
set TotalShare = (sum(Share) from SharePage where "ShareButtonID" = ShareButtonID of updated/inserted record)) 
where ID = ShareButtonID of updated/inserted record)`

感谢阅读!

【问题讨论】:

  • 为什么还要保存这些信息?为什么不在需要的时候用聚合查询来查询呢?
  • 你做的太多了+为什么触发?您可以简单地更新存储过程中修改 SharePage 表的父表。
  • 谢谢大家。这是最好和最简单的方法:D

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


【解决方案1】:

让我先说我同意 Mureinik。除非您使用简单的 group by 查询获取份额总和的性能非常糟糕,否则我不建议将该总和保存在 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 上的任何插入、更新或删除语句完成后触发。由于是after触发器,所以根本不需要处理inserted和delete的表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多