SQL Server 默认日期时间戳?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7002477/
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
SQL Server default date time stamp?
提问by Snow_Mac
I have a field that when something is inserted I want it to get the current Date & Time and insert this into the database. Is there a way to get the date & time, and set it as the default value?
我有一个字段,当插入某些内容时,我希望它获取当前的日期和时间并将其插入到数据库中。有没有办法获取日期和时间,并将其设置为默认值?
Currently the default value is: (getdate()) Which sets only the date. How do I also set the time?
当前默认值是: (getdate()) 只设置日期。我还怎么设置时间?
回答by JNK
GETDATE()
is a date and time in SQL Server.
GETDATE()
是 SQL Server 中的日期和时间。
Run SELECT GETDATE()
to verify this.
运行SELECT GETDATE()
以验证这一点。
What is the datatype of your field? If it's DATE
then it will not hold time values as well.
你的字段的数据类型是什么?如果是,DATE
那么它也不会保存时间值。
回答by Andomar
One easy way is to give the field a default constraint:
一种简单的方法是给字段一个默认约束:
create table YourTable
(
... other columns ...
CreateDt datetime default getdate(),
... other columns ...
)
A disadvantage of this method is that you can overwrite the value by specifying it in an insert
clause.
这种方法的一个缺点是您可以通过在insert
子句中指定它来覆盖该值。
回答by Dasun
Personally I would like to use GETUTCDATE() instead GETDATE() to avoid confusions.
我个人想使用 GETUTCDATE() 代替 GETDATE() 以避免混淆。
回答by Ariel
SYSDATETIME()
will get the current date and time.
SYSDATETIME()
将获得当前日期和时间。
Make sure the data type of the column is datetime
, and not just date
or it won't be able to hold a datetime.
确保列的数据类型是datetime
, 而不仅仅是date
,否则将无法保存日期时间。
回答by ain
Most SQL implementations (engines) do have CURRENT_TIMESTAMP
function.
大多数 SQL 实现(引擎)确实具有CURRENT_TIMESTAMP
功能。