sql server 2008在两个日期列上运行

vbN*_*bie 1 sql sql-server-2005

我想为一个包含三列的表创建一个函数,如下所示:

insertDate datetime
updateDate datetime
activity   integer
Run Code Online (Sandbox Code Playgroud)

我想通过获取两个日期列的差异来更新活动列...基本上updateDate - insertDate =活动列中活动的天数.我不知道如何启动它,只要插入新的insertDate或updateDate,它就需要运行.

Bra*_*rad 7

您可以[InsertDate]使用默认值GETDATE()填充,[UpdateDate]并在更新列时填充当前日期(因为您正在使用过程(wink),这非常容易控制).如果您没有使用程序并想要控制.在该[UpdateDate]列中,您可以使用触发器填充该列.

Activity列成为计算字段:

DATEDIFF(day, [InsertDate], [UpdateDate])
Run Code Online (Sandbox Code Playgroud)

DATEDIFF

计算列


从MSDNabout计算列:

Unless otherwise specified, computed columns are virtual columns that are
not physically stored in the table. Their values are recalculated every
time they are referenced in a query. The Database Engine uses the PERSISTED
keyword in the CREATE TABLE and ALTER TABLE statements to physically store
computed columns in the table. Their values are updated when any columns
that are part of their calculation change. By marking a computed column as
PERSISTED, you can create an index on a computed column that is
deterministic but not precise.
Run Code Online (Sandbox Code Playgroud)