用于维护修改历史记录的 SQL 触发器
我有三个表:
Table1: Customers (CustomerId, Name, CustomerAddress)
Table2: AccountManagers(ManagerId, Name)
Table3: CustomerAccountManagers (CustomerId, ManagerId, Remarks)
Table4: CustomerHistory(CustomerAddress, ManagerId, Date)
CustomerHistory 表用于存储对“CustomerAddress”或“ManagerId”所做的任何更改,例如 CustomerAddress 从“Address1”更新为“Address2”,或者 CustomerAccountManager 从“Manager1”更改为“Manager2”。
我需要通过 SQL 触发器将更改存储在 CustomerHistory 表中。问题是我应该在哪张桌子上放置触发器?请注意,更改是同时对“客户”表和“客户”表进行的。 “客户帐户经理”。
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,
CustomerHistory
表可能还应该包含CustomerId
,以便可以将历史记录追溯到正确的客户。您需要两个触发器:一个在
CustomerAccountManagers
上,另一个在Customers
上。如果您可以保证它们的执行顺序,那就没问题:第一个触发器将插入,第二个触发器将更新历史记录。如果您不能保证顺序,事情就会变得复杂,因为每个触发器都必须:1)尝试插入新记录,如果失败2)更新现有记录。您必须保护自己免受另一个触发器的间歇性插入的影响,这可能意味着在具有可序列化隔离级别的事务中运行(锁定整个表)。这很容易出现死锁,因此最好使用两个历史表,正如其他人已经建议的那样。
First of all, the
CustomerHistory
table should probably containCustomerId
as well, so that a history record can be tracked back to the proper customer.You'll need two triggers: one on
CustomerAccountManagers
and one onCustomers
. If you can guarantee the order in which they are executed it's fine: the first trigger will insert, the second update the history record.If you cannot guarantee the order, things get complicated, as each trigger would have to: 1) try to insert a new record, and failing that 2) update the existing. You'd have to protect yourself from the intermittent insertion by another trigger and this likely means running within a transaction with serializable isolation level (locking the whole table). This is deadlock-prone, so it's really better to use two history tables, as others already suggested.
对于每个普通表,您应该有不同的历史表。
然后,您可以在每个普通表中放置一个触发器。
最后,如果需要,您可以创建一个视图
CustomerHistory
连接不同的历史表。You should have different historic tables for each normal table you have.
Then you can place a trigger in each normal table.
Finally, if you need, you can create a view
CustomerHistory
joining the different historic tables.您需要将触发器添加到表中,其中数据更改将“触发”执行某些操作的需要。
因此,Customers 表上的触发器用于跟踪 CustomerAddress 更改,而 CustomerAccountManagers 上的触发器则在 ManagerId 更改时触发。
You need to add your trigger to the table where data changes will "trigger" a need to do something.
So a trigger on the Customers table to track CustomerAddress changes and a trigger on CustomerAccountManagers when the ManagerId is changed.