有沒有辦法在Sql Server中將列的默認值設置爲DateTime.Now
?使用當前日期作爲列的默認值
實施例:
table Event
Id int (auto-increment) not null
Description nvarchar(50) not null
Date datetime not null
線:
Insert into Event(Description) values('teste');
應插入一行和日期值應爲當前日期。
有沒有辦法在Sql Server中將列的默認值設置爲DateTime.Now
?使用當前日期作爲列的默認值
實施例:
table Event
Id int (auto-increment) not null
Description nvarchar(50) not null
Date datetime not null
線:
Insert into Event(Description) values('teste');
應插入一行和日期值應爲當前日期。
使用GETDATE()函數作爲值添加默認約束。
ALTER TABLE myTable
ADD CONSTRAINT CONSTRAINT_NAME
DEFAULT GETDATE() FOR myColumn
在PostgreSQL中,它將是: 「alter table myTable add column mydatecol date default現在();」 ..我只添加這個評論,因爲在問題的標題中沒有提到Sql-Server。可以幫助PostgreSQL用戶... – alfonx 2011-07-09 12:12:29
如果該列已經存在於表中,這將是表單,並且如果在INSERT語句(或從CURSOR插入)中忽略該值,則沒有限制來設置默認值。 – 2013-06-08 11:34:38
有沒有辦法通過管理工作室來做到這一點? – Steam 2013-10-26 05:28:40
您可以使用:
Insert into Event(Description,Date) values('teste', GETDATE());
另外,你可以改變你的表格,使得 '日期' 有一個默認, 「GETDATE()」
確定將「默認值或綁定」設置爲「getdate()」 – Moji 2015-08-17 15:28:28
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
)
此表單設置了一個未命名的約束。最好命名約束:'[...] OrderDate DATE CONSTRAINT DF_Orders_date DEFAULT GETDATE()[...]' – 2013-06-08 11:35:45
選擇表列名您想要獲取當前日期的默認值的地方
ALTER TABLE
[dbo].[Table_Name]
ADD CONSTRAINT [Constraint_Name]
DEFAULT (getdate()) FOR [Column_Name]
ALTER TABLE查詢
Alter TABLE [dbo].[Table_Name](
[PDate] [datetime] Default GetDate())
該鏈接可能是有用的太 - HTTP:/ /blog.sqlauthority.com/2013/05/10/sql-server-adding-column-defaulting-to-current-datetime-in-table/ – Steam 2013-10-26 05:30:16