use current date as default value for a column

2020-05-19 11:10发布

Is there a way to set the default value of a column to DateTime.Now in Sql Server?

Example:

table Event
Id int (auto-increment) not null
Description nvarchar(50) not null
Date datetime not null

The line:

Insert into Event(Description) values('teste');

should insert a row and the Date value should be the current date.

8条回答
贼婆χ
2楼-- · 2020-05-19 11:25
CREATE TABLE Orders(
    O_Id int NOT NULL,
    OrderNo int NOT NULL,
    P_Id int,
    OrderDate date DEFAULT GETDATE() // you can set default constraints while creating the table
)
查看更多
够拽才男人
3楼-- · 2020-05-19 11:27

Table creation Syntax can be like:

Create table api_key(api_key_id INT NOT NULL IDENTITY(1,1) 
PRIMARY KEY, date_added date DEFAULT 
GetDate());

Insertion query syntax can be like:

Insert into api_key values(GETDATE());
查看更多
4楼-- · 2020-05-19 11:35

Select Table Column Name where you want to get default value of Current date

 ALTER TABLE 
 [dbo].[Table_Name]
 ADD  CONSTRAINT [Constraint_Name] 
 DEFAULT (getdate()) FOR [Column_Name]

Alter Table Query

Alter TABLE [dbo].[Table_Name](
    [PDate] [datetime] Default GetDate())
查看更多
走好不送
5楼-- · 2020-05-19 11:38

Add a default constraint with the GETDATE() function as value.

ALTER TABLE myTable 
  ADD CONSTRAINT CONSTRAINT_NAME
    DEFAULT GETDATE() FOR myColumn
查看更多
Explosion°爆炸
6楼-- · 2020-05-19 11:42

Right click on the table and click on Design,then click on column that you want to set default value.

Then in bottom of page in column properties set Default value or binding to : 'getdate()'

查看更多
淡お忘
7楼-- · 2020-05-19 11:44

You can use:

Insert into Event(Description,Date) values('teste', GETDATE());

Also, you can change your table so that 'Date' has a default, "GETDATE()"

查看更多
登录 后发表回答