且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将日期时间插入 SQL 数据库表中?

更新时间:2023-10-15 09:24:04

DateTime 值应该像用单引号括起来的字符串一样插入:

DateTime values should be inserted as if they are strings surrounded by single quotes:

'20100301'

SQL Server 允许许多可接受的日期格式,并且大多数开发库都提供了一系列类或函数来正确插入日期时间值.但是,如果您是手动操作,则使用 DateFormat 区分日期格式和使用通用格式很重要:

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:

Set DateFormat MDY --indicates the general format is Month Day Year

Insert Table( DateTImeCol )
Values( '2011-03-12' )

通过设置日期格式,SQL Server 现在假定我的格式是 YYYY-MM-DD 而不是 YYYY-DD-MM.

By setting the dateformat, SQL Server now assumes that my format is YYYY-MM-DD instead of YYYY-DD-MM.

设置日期格式

SQL Server 还可以识别始终以相同方式解释的通用格式:YYYYMMDD 例如20110312.

SQL Server also recognizes a generic format that is always interpreted the same way: YYYYMMDD e.g. 20110312.

如果您询问如何使用 T-SQL 插入当前日期和时间,那么我建议您使用关键字 CURRENT_TIMESTAMP.例如:

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:

Insert Table( DateTimeCol )
Values( CURRENT_TIMESTAMP )