如何避免每次访问表时都更新GETDATE()[SQL Server 2014]
我正在使用SQL Server 2014。我希望创建一个列,自动捕获创建记录的时间,并保存该值。我尝试使用GETDATE()函数,但我知道这无法工作,因为它不是确定性的如何避免每次访问表时都更新GETDATE()[SQL Server 2014],sql,sql-server,getdate,icomparer,Sql,Sql Server,Getdate,Icomparer,我正在使用SQL Server 2014。我希望创建一个列,自动捕获创建记录的时间,并保存该值。我尝试使用GETDATE()函数,但我知道这无法工作,因为它不是确定性的 目标是使用此值跟踪表中的最新记录。我试图使用rowversion(timestamp)来实现这一点,但我也无法使用它,因为在C中,这种类型没有实现IComparer。你能推荐一个我可以使用的功能或技术吗。我感谢所有的帮助。谢谢。如果您愿意: create table t ( . . . createdAt dat
目标是使用此值跟踪表中的最新记录。我试图使用rowversion(timestamp)来实现这一点,但我也无法使用它,因为在C中,这种类型没有实现IComparer。你能推荐一个我可以使用的功能或技术吗。我感谢所有的帮助。谢谢。如果您愿意:
create table t (
. . .
createdAt datetime
);
insert into t( . . ., createdAt)
select . . . , getdate();
create table t (
. . .
createdAt datetime default getdate()
);
insert into t( . . .)
select . . . ;
然后插入日期在列中
如果您这样做:
create table t (
. . .
createdAt datetime
);
insert into t( . . ., createdAt)
select . . . , getdate();
create table t (
. . .
createdAt datetime default getdate()
);
insert into t( . . .)
select . . . ;
那么你就有了完全相同的行为
如果需要具有当前日期时间的列,则可以执行以下操作:
create table t (
. . .
createdAt datetime default getdate(),
cur_datetime as (getdate())
);
使用datetime查找表中的最新记录不是一个好主意。在下面的示例中,所有记录在ts字段中将具有相同的值
declare @t table (id int identity, name nvarchar(50), ts datetime default getdate())
insert @t (name) values ('item #1'),('item #2'),('item #3'),('item #4');
select * from @t
要查找最新插入/更新的记录,应使用时间戳字段。您可以将时间戳转换为bigint
declare @t table (id int identity, name nvarchar(50), ts datetime default getdate(), ts1 timestamp)
insert @t (name) values ('item #1'),('item #2'),('item #3'),('item #4');
select id, name, ts, cast(ts1 as bigint) as ts1 from @t
这通常通过插入行时的Getdate()来处理。除非你改变它,否则它不会改变。该列可以将其作为默认值。它对您有什么变化?@scsimon它在变化,因为他们将它作为非持久化计算列。因此,每次选择时都会重新评估@MartinSmith good thinking.hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh。演员阵容正是我所缺少的。现在我可以毫无问题地在C#中使用“OrderBy”子句了。