SQL Server 触发器。需要帮助
我有一个包含以下列的表格:
- 债务
- 已付
- 仍存
每当更新 paid
列时,我需要使用以下计算 debt
重新计算 remained
减去付费
有人可以帮助我实现这一目标吗?
I have a table with these columns:
- debt
- paid
- remained
Whenever the paid
column is updated I need to recalculate the remained
using the following calculation debt
minus paid
Could someone help me achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以考虑使用计算列 。
这篇文章具有从头开始创建或添加到现有架构的语法,大致如下的
You could consider a computed column instead.
This article has the syntax for creating from scratch or adding to an existing schema, along the lines of
给定表
以下触发器将重新计算字段 Remainder
您还可以将 Remainder 定义为 计算持久< /a> 列,这将具有类似的效果,而没有触发器的副作用
Given table
The following trigger will recalculate field Remainder
You could also define Remainder as a Computed persisted column, which would have a similar effect without the side effects of triggers
当 SQL 可以为您执行计算时,为什么要在触发器中执行计算,并且您不必担心触发器被禁用等:
这称为计算列
Why perform a calculation in a trigger when SQL can do it for you, and you don't have to worry about triggers being disabled, etc:
This is called a computed column
http://msdn.microsoft.com/en-us/library/ms189799.aspx
http:// benreichelt.net/blog/2005/12/13/making-a-trigger-fire-on-column-change/
http://msdn.microsoft.com/en-us/library/ms189799.aspx
http://benreichelt.net/blog/2005/12/13/making-a-trigger-fire-on-column-change/
计算列可能很好,但它们是动态计算的并且不会存储在任何地方,对于一些执行长时间计算的大型查询来说,在由触发器控制的“Remained”中具有物理非规范化值可能比计算列更好。
在触发器中,请记住仅更新已更新的行,您可以通过触发器中可用的虚拟表 Inserted Deleted 访问这些行。
Computed columns can be good but they are calculated on the fly and arent stored anywhere, for some big queries that perform long calculations having a physical denormalyzed value in Remained controlled by trigger can be better than computed columns.
In your trigger remember to only update rows that were updated , you access those by virtual table Inserted Deleted available in triggers.