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条回答
\"骚年 ilove
2楼-- · 2020-05-19 11:45

To use the current date as the default for a date column, you will need to:

1- open table designer

2- select the column

3- go to column proprerties

4- set the value of Default value or binding propriete To (getdate())

enter image description here

查看更多
Juvenile、少年°
3楼-- · 2020-05-19 11:47

I have also come across this need for my database project. I decided to share my findings here.

1) There is no way to a NOT NULL field without a default when data already exists (Can I add a not null column without DEFAULT value)

2) This topic has been addressed for a long time. Here is a 2008 question (Add a column with a default value to an existing table in SQL Server)

3) The DEFAULT constraint is used to provide a default value for a column. The default value will be added to all new records IF no other value is specified. (https://www.w3schools.com/sql/sql_default.asp)

4) The Visual Studio Database Project that I use for development is really good about generating change scripts for you. This is the change script created for my DB promotion:

GO
PRINT N'Altering [dbo].[PROD_WHSE_ACTUAL]...';

GO
ALTER TABLE [dbo].[PROD_WHSE_ACTUAL]
    ADD [DATE] DATE DEFAULT getdate() NOT NULL;

-

Here are the steps I took to update my database using Visual Studio for development.

1) Add default value (Visual Studio SSDT: DB Project: table designer) enter image description here

2) Use the Schema Comparison tool to generate the change script.

code already provided above

3) View the data BEFORE applying the change. enter image description here

4) View the data AFTER applying the change. enter image description here

查看更多
登录 后发表回答