Date / Timestamp to record when a record was added

2020-02-03 05:17发布

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条回答
小情绪 Triste *
2楼-- · 2020-02-03 05:33

You can pass GetDate() function as an parameter to your insert query e.g

Insert into table (col1,CreatedOn) values (value1,Getdate())
查看更多
成全新的幸福
3楼-- · 2020-02-03 05:38

You can use a datetime field and set it's default value to GetDate().

CREATE TABLE [dbo].[Test](
    [TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_Test_TimeStamp] DEFAULT (GetDate()),
    [Foo] [varchar](50) NOT NULL
) ON [PRIMARY]
查看更多
The star\"
4楼-- · 2020-02-03 05:39

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.

e.g.

CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)
查看更多
Luminary・发光体
5楼-- · 2020-02-03 05:43

You can make a default constraint on this column that will put a default getdate() as a value.

Example:

alter table dbo.TABLE 
add constraint df_TABLE_DATE default getdate() for DATE_COLUMN
查看更多
冷血范
6楼-- · 2020-02-03 05:56

you can use DateAdd on a trigger or a computed column if the timestamp you are adding is fixed or dependent of another column

查看更多
登录 后发表回答