简体   繁体   English

是否有 ANSI/ISO SQL 语法来获取当前时间?

[英]Is there an ANSI/ISO SQL syntax to obtain the current time?

I would like to get a DB's current time, using Standard SQL.我想使用标准 SQL 获取数据库的当前时间。 The result must either be in UTC or come with timezone information.结果必须是 UTC 或带有时区信息。 Is that possible?那可能吗? If yes, how?如果是,如何?


Apparently, there's CURRENT_TIMESTAMP, which is ANSI SQL, but is there an ANSI SQL syntax to retrieve just that?显然,有 CURRENT_TIMESTAMP,即 ANSI SQL,但是否有 ANSI SQL 语法来检索它? Some DBMS support select CURRENT_TIMESTAMP , others require select CURRENT_TIMESTAMP from DUAL .一些 DBMS 支持select CURRENT_TIMESTAMP ,其他需要select CURRENT_TIMESTAMP from DUAL Any way to do this DBMS-independent?有什么方法可以做到这一点独立于 DBMS?

Short answer:简短的回答:

There is no standard function to do this (as far as I know).没有标准的 function 可以做到这一点(据我所知)。 Each vendor implemented their own functions to handle date and time, including retrieving the current time.每个供应商都实现了自己的函数来处理日期和时间,包括检索当前时间。

Possible solution (given you have control over the database):可能的解决方案(假设您可以控制数据库):

You can create a view containing one record using (or a function proxying) the vendor specific function and use that as a source in your application.您可以使用(或 function 代理)供应商特定的 function 创建包含一条记录的视图,并将其用作应用程序中的源。

For example (SQL Server)例如(SQL 服务器)

CREATE VIEW dbo.[DateTime] AS
SELECT
  SYSUTCDATETIME() AS UTCDateTime
;

or in (MySQL)或在(MySQL)

CREATE VIEW DateTime AS
SELECT
  UTC_TIMESTAMP as UTCDateTime
;

The ANSI/ISO SQL standard has CURRENT_TIME to get time with timezone information, and LOCALTIME to get time without timezone information. ANSI/ISO SQL 标准具有CURRENT_TIME以获取具有时区信息的时间,并LOCALTIME以获取具有时区信息的时间。

However, many products have their own functions instead.但是,许多产品都有自己的功能。

Assuming you use SQL server:假设您使用 SQL 服务器:

SELECT CONVERT(varchar(10), GETUTCDATE(), 108)

The ANSI SQL way of doing this is to use the VALUES statement.执行此操作的 ANSI SQL 方法是使用VALUES语句。 This is similar to the SELECT statement, in that it returns a result set.这类似于SELECT语句,因为它返回一个结果集。 But it doesn't reference any table.但它没有引用任何表格。 It's the standard way of doing something like what Oracle's DUAL pseudo-table is used for.这是执行类似于 Oracle 的DUAL伪表的标准方法。

Here's a demo using MySQL 8.0:这是使用 MySQL 8.0 的演示:

mysql> VALUES ROW(CURRENT_TIMESTAMP);
+---------------------+
| column_0            |
+---------------------+
| 2021-11-22 14:56:58 |
+---------------------+

See:看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM