如何将日期时间插入 SQL 数据库表中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5287427/
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
how to insert datetime into the SQL Database table?
提问by Srihari
How can I insert datetime into the SQL Database table ? Is there a way to insert this query through the insert command in C# / .NET?
如何将日期时间插入 SQL 数据库表中?有没有办法通过 C#/.NET 中的插入命令插入此查询?
回答by Thomas
DateTime values should be inserted as if they are strings surrounded by single quotes:
应该插入 DateTime 值,就好像它们是用单引号括起来的字符串一样:
'20100301'
SQL Server allows for many accepted date formats and it should be the case that most development libraries provide a series of classes or functions to insert datetime values properly. However, if you are doing it manually, it is important to distinguish the date format using DateFormat
and to use generalized format:
SQL Server 允许许多可接受的日期格式,并且大多数开发库都提供了一系列类或函数来正确插入日期时间值。但是,如果您手动执行此操作,重要的是要区分使用的日期格式DateFormat
和使用通用格式:
Set DateFormat MDY --indicates the general format is Month Day Year
Insert Table( DateTImeCol )
Values( '2011-03-12' )
By setting the dateformat, SQL Server now assumes that my format is YYYY-MM-DD
instead of YYYY-DD-MM
.
通过设置日期格式,SQL Server 现在假定我的格式YYYY-MM-DD
不是YYYY-DD-MM
.
SQL Server also recognizes a generic format that is always interpreted the same way: YYYYMMDD
e.g. 20110312
.
SQL Server 还识别始终以相同方式解释的通用格式:YYYYMMDD
例如20110312
.
If you are asking how to insert the current date and time using T-SQL, then I would recommend using the keyword CURRENT_TIMESTAMP
. For example:
如果您询问如何使用 T-SQL 插入当前日期和时间,那么我建议您使用关键字CURRENT_TIMESTAMP
。例如:
Insert Table( DateTimeCol )
Values( CURRENT_TIMESTAMP )
回答by Abe Miessler
You will need to have a datetimecolumn in a table. Then you can do an insert like the following to insert the current date:
您将需要在表中有一个日期时间列。然后,您可以执行如下插入操作以插入当前日期:
INSERT INTO MyTable (MyDate) Values (GetDate())
If it is not today's date then you should be able to use a string and specify the date format:
如果它不是今天的日期,那么您应该能够使用字符串并指定日期格式:
INSERT INTO MyTable (MyDate) Values (Convert(DateTime,'19820626',112)) --6/26/1982
You do not always need to convert the string either, often you can just do something like:
您也不总是需要转换字符串,通常您可以执行以下操作:
INSERT INTO MyTable (MyDate) Values ('06/26/1982')
And SQL Server will figure it out for you.
SQL Server 会为您解决这个问题。
回答by bensiu
if you got actuall time in mind GETDATE()
would be the function what you looking for
如果您考虑到实际时间GETDATE()
将是您正在寻找的功能
回答by Ranatunge
myConn.Execute "INSERT INTO DayTr (dtID, DTSuID, DTDaTi, DTGrKg) VALUES (" & Val(txtTrNo) & "," & Val(txtCID) & ", '" & Format(txtTrDate, "yyyy-mm-dd") & "' ," & Val(Format(txtGross, "######0.00")) & ")"
Done in vb with all text type variables.
使用所有文本类型变量在 vb 中完成。