This question already has an answer here:
这个问题在这里已有答案:
- How do I add a “last updated” column in a SQL Server 2008 R2 table? 2 answers
- 如何在SQL Server 2008 R2表中添加“上次更新”列? 2个答案
Does anyone know of a function as such that I can use to add an automatic date and timestamp in a column for when a user adds a record to the database table?
有没有人知道一个函数,我可以用来在列中为用户添加记录到数据库表时添加自动日期和时间戳?
5 个解决方案
#1
40
You can create a non-nullable DATETIME column on your table, and create a DEFAULT constraint on it to auto populate when a row is added.
您可以在表上创建一个不可为空的DATETIME列,并在其上创建一个DEFAULT约束,以便在添加行时自动填充。
e.g.
例如
CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)
#2
3
You can use a datetime
field and set it's default value to GetDate()
.
您可以使用datetime字段并将其默认值设置为GetDate()。
CREATE TABLE [dbo].[Test](
[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_Test_TimeStamp] DEFAULT (GetDate()),
[Foo] [varchar](50) NOT NULL
) ON [PRIMARY]
#3
3
You can make a default constraint on this column that will put a default getdate() as a value.
您可以在此列上创建一个默认约束,将默认的getdate()作为值。
Example:
例:
alter table dbo.TABLE
add constraint df_TABLE_DATE default getdate() for DATE_COLUMN
#4
3
You can pass GetDate()
function as an parameter to your insert query e.g
您可以将GetDate()函数作为参数传递给插入查询,例如
Insert into table (col1,CreatedOn) values (value1,Getdate())
#5
0
you can use DateAdd on a trigger or a computed column if the timestamp you are adding is fixed or dependent of another column
如果要添加的时间戳是固定的或依赖于另一列,则可以在触发器或计算列上使用DateAdd
#1
40
You can create a non-nullable DATETIME column on your table, and create a DEFAULT constraint on it to auto populate when a row is added.
您可以在表上创建一个不可为空的DATETIME列,并在其上创建一个DEFAULT约束,以便在添加行时自动填充。
e.g.
例如
CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)
#2
3
You can use a datetime
field and set it's default value to GetDate()
.
您可以使用datetime字段并将其默认值设置为GetDate()。
CREATE TABLE [dbo].[Test](
[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_Test_TimeStamp] DEFAULT (GetDate()),
[Foo] [varchar](50) NOT NULL
) ON [PRIMARY]
#3
3
You can make a default constraint on this column that will put a default getdate() as a value.
您可以在此列上创建一个默认约束,将默认的getdate()作为值。
Example:
例:
alter table dbo.TABLE
add constraint df_TABLE_DATE default getdate() for DATE_COLUMN
#4
3
You can pass GetDate()
function as an parameter to your insert query e.g
您可以将GetDate()函数作为参数传递给插入查询,例如
Insert into table (col1,CreatedOn) values (value1,Getdate())
#5
0
you can use DateAdd on a trigger or a computed column if the timestamp you are adding is fixed or dependent of another column
如果要添加的时间戳是固定的或依赖于另一列,则可以在触发器或计算列上使用DateAdd