我想對於有三列除其他表上創建函數功能如下:SQL Server 2008中的兩個日期列
insertDate datetime
updateDate datetime
activity integer
我想更新活動柱採取的區別兩個日期列...基本上updateDate - insertDate =活動列中有多少天的活動。我不知道如何啓動它,只要插入一個新的insertDate或updateDate,它就需要運行。
我想對於有三列除其他表上創建函數功能如下:SQL Server 2008中的兩個日期列
insertDate datetime
updateDate datetime
activity integer
我想更新活動柱採取的區別兩個日期列...基本上updateDate - insertDate =活動列中有多少天的活動。我不知道如何啓動它,只要插入一個新的insertDate或updateDate,它就需要運行。
您可以用GETDATE()
默認值填充[InsertDate]
,並在更新列中的當前日期填充[UpdateDate]
(因爲你正在使用的程序(眨眼),這是很容易控制)。如果你不使用程序並想要控制。在[UpdateDate]
列中,您可以使用觸發器來填充該列。
讓Activity
列是計算的字段:
DATEDIFF(day, [InsertDate], [UpdateDate])
從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.
由於所需的所有數據位於表格的同一行,因此您可以創建computed column。如果您想要更新實際列值,則需要查看triggers。
將此代碼置於觸發器中。
update MyTable
set updateDate = GETDATE()
, activity = select (DATEDIFF(DAY, insertDate, GETDATE()))
+1對於計算的外場觀念。我沒有想到它,甚至比觸發方法更好的解決方案。 =) – 2010-12-06 15:26:23