【问题标题】:Trigger or computed column?触发器或计算列?
【发布时间】:2012-12-12 13:03:31
【问题描述】:

我在 SQL Server 2008 中有一个表 employeeswipe_tbl,其中包含以下列:

create employeeswipe_tbl swipepk int (
swipepk int primary ,
empid  int,
dateofswipe date ,
intime datetime,
outime datetime,
logduration  time
)

当员工登录intime, empid, dateofswipe 时,当outime 注销时,swipepk 会更新

现在我想要的是,当我更新 outtime 时,logduration 将自动计算为

logduration  = outtime - intime

我正在考虑一些想法,例如计算列或触发器。考虑到我是初学者,谁能给出一个好的选择?

【问题讨论】:

  • 两个日期和时间之间的差异是时间跨度,而不是日期和时间。
  • @Damien_The_Unbeliever 我正在编辑并制作持续时间

标签: c# sql-server-2008


【解决方案1】:

计算列通常比触发器更好。可以禁用触发器。计算列“总是”正确:

create table employeeswipe_tbl (
swipepk int primary key,
empid  int,
intime datetime,
outime datetime,
dateofswipe AS CONVERT(date,intime) ,
logduration AS DATEDIFF(second,intime,outime)
)

正如我的评论中所指出的,两个datetimes 之间的区别将是一个时间跨度,而不是另一个datetime。 SQL Server 中没有时间跨度类型,因此最好以秒为单位保持差异 - 在显示期间将其格式化为小时、分钟和秒。例如,如果您需要将几行有价值的数据相加,这将变得更加容易。


旁注 - 我也在考虑将 dateofswipe 设为计算列 - 它不只是 intime 的日期部分吗?

【讨论】:

  • dateofswipe 是 intime 的一个日期部分
  • ALTER TABLE EmployeSwipeDaily_tbl ADD Duration1 AS DATEDIFF(second,EmployeSwipeDaily_tbl.intime,EmployeSwipeDaily_tbl.outtime)
  • @sreenathsreenath - 你不应该包含表名。计算列只能引用同一个表中的其他列。
猜你喜欢
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多