SQL 插入日期的默认 getdate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4672103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default getdate for Insert date
提问by p.campbell
I have a table called sample and it has a column called [__INSERT_DATE] which is null. Now I want to alter the column with default as getdate()
. When I tried the following it gave me an error.
我有一个名为 sample 的表,它有一个名为 [__INSERT_DATE] 的列,该列为空。现在我想更改默认为getdate()
. 当我尝试以下操作时,它给了我一个错误。
ALTER TABLE sample
ALTER COLUMN [__INSERT_DATE] [datetime] DEFAULT (getdate()) NULL)
Can anyone tell me what the problem is?
谁能告诉我是什么问题?
回答by p.campbell
Try this:
尝试这个:
ALTER TABLE MyTable ADD CONSTRAINT
DF_MyTable_Inserted DEFAULT GETDATE() FOR INSERT_DATE
GO
This assumes your table is named MyTable
, the column is INSERT_DATE
, and the name of the contstraint is to be DF_MyTable_Inserted
这假设您的表已命名MyTable
,INSERT_DATE
列为 ,并且约束的名称为DF_MyTable_Inserted
回答by J.Ray
Try this:
尝试这个:
ALTER TABLE sample ADD CONSTRAINT DF_sample___INSERT_DATE DEFAULT(GETDATE()) FOR __INSERT_DATE
回答by DOK
回答by Andrew
ALTER TABLE sample
ALTER COLUMN [__INSERT_DATE] [datetime] DEFAULT (getdate()) NULL)
ALTER TABLE sample
ALTER COLUMN [__INSERT_DATE] [datetime] DEFAULT (getdate()) NULL)
You have one too many closing brackets in the above statement. There are 2 of these -> ( but 3 of these -> )
上面的语句中有太多的右括号。其中有 2 个 -> (但其中有 3 个 -> )
回答by Arun Prasad E S
回答by Md Shahriar
(Your_Date_Column) Make it Null / Not Null and give default value GetDate() but still it will not work. You have to create a trigger like this,
(Your_Date_Column) 使其为 Null / Not Null 并提供默认值 GetDate() 但它仍然不起作用。你必须像这样创建一个触发器,
CREATE TRIGGER [dbo].[Trigger_Date] ON [dbo].[TableName] FOR INSERT AS BEGIN
CREATE TRIGGER [dbo].[Trigger_Date] ON [dbo].[TableName] FOR INSERT AS BEGIN
Declare @Id int
set @Id = (select Id from inserted)
Update [dbo].[TableName]
Set Your_Date_Column = GetDate()
Where Id = @Id
END
回答by Jennifer S
Does getdate() return the correct date and time datatype for your declared column? There are some new date and time datatypes in SQL Server 2008.
getdate() 是否为您声明的列返回正确的日期和时间数据类型?SQL Server 2008 中有一些新的日期和时间数据类型。
Here's an article that explains some of the differences.
这是一篇解释一些差异的文章。
http://www.sql-server-performance.com/articles/dev/datetime_2008_p1.aspx
http://www.sql-server-performance.com/articles/dev/datetime_2008_p1.aspx