SQL Server 2005 -修改日期列-使用计算列是实现此目的的正确方法吗?
我只想在插入或更新记录时自动填充“ModifyDate”列。
我应该使用触发器还是可以使用计算列?
(使用 SSMS2005 和 SQL Server 2005 Express)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
INSERTed 部分很简单 - 只需在该列上定义一个默认值,并且当您插入新行时,不要为该列指定值。
UPDATE 部分比较棘手 - 您必须编写一个 在 UPDATE 时触发的触发器,然后更新该列。我认为在 SQL Server 中没有其他方法可以做到这一点。
问题是:您真的需要实际的日历日期吗?如果没有,如果您只想有一个“标记”来确定行是否已更改,请查看 ROWVERSION 列类型(以前称为
TIMESTAMP
)。我真的不明白如何为此使用计算列 - 您必须将该日期存储在某处,并使其与 INSERT 和每个后续更新保持同步 - 只有触发器才能做到这一点。
The INSERTed part is easy - just define a default value on that column, and when you insert a new row, do not specify a value for that column.
The UPDATE part is trickier - you will have to write a trigger that fires ON UPDATE, and then updates that column. I don't think there's any other way to do this in SQL Server.
Question is: do you really need the actual calendar date? If not, if you only want to have a "marker" as to whether or not a row has changed, check out the ROWVERSION column type (formerly known as
TIMESTAMP
) instead.I don't really see how you could use a computed column for this - you have to store that date somewhere, and keep it current with INSERT and each subsequent UPDATE - only a trigger will manage to do this.
我建议远离触发器并使用服务器 getDate 函数通过存储过程设置“修改日期”列。
示例:
更新客户集 FirstName = 'Jim', LastName = 'Jones', DateModified = getDate()
I would suggest staying away from triggers and set the Date Modified column with a stored procedure using the server getDate function.
Example:
Update Customers Set FirstName = 'Jim', LastName = 'Jones', DateModified = getDate()
我想你的意思是默认约束而不是计算列。
如果是这样,那没关系。我更喜欢这样做。一个可能的缺点是客户端可以覆盖默认值,但如果您不信任客户端,您也可以将表访问包装在存储过程中。
触发器也可以工作,但触发器往往会产生额外的复杂性。包括触发器在内的编码错误是最困难的数据库问题之一。
I suppose you mean a default constraint instead of a computed column.
If so, that's OK. I prefer to do it like that. One possible disadvantage is that a client can override the default value, but if you don't trust the client, you might as well wrap table access in stored procedures.
Triggers will work too, but triggers tend to generate extra complexity. Coding errors that include triggers are among the hardest database issues out there.