摘要:在本教程中,你将学习如何使用 SQL CURRENT_TIMESTAMP
函数获取当前日期和时间。
要获取数据库服务器的当前日期和时间,可以如下所示使用 SQL CURRENT_TIMESTAMP
函数
CURRENT_TIMESTAMP
Code language: SQL (Structured Query Language) (sql)
CURRENT_TIMESTAMP
函数是 SQL 标准函数,几乎所有数据库系统均支持,例如 DB2、Firebird、Microsoft SQL Server、MySQL、Oracle、PostgreSQL 和 SQLite。
以下语句返回数据库服务器的当前日期和时间
SELECT CURRENT_TIMESTAMP
AS 'Current date and time';
Code language: SQL (Structured Query Language) (sql)
这是输出
Current date and time
-----------------------
2018-07-21 18:12:42.023
Code language: SQL (Structured Query Language) (sql)
请注意,在 Oracle 中,你需要添加 FROM dual
子句,如下所示
SELECT
CURRENT_TIMESTAMP
AS 'Current date and time'
FROM
dual;
Code language: SQL (Structured Query Language) (sql)
CURRENT_TIMESTAMP
通常用于设置表中 DATETIME
或 TIMESTAMP
列的默认值。
例如,以下语句创建一个新表,其中包含 created_at
列,该列将日期和时间作为默认值。
CREATE TABLE posts(
id INT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Code language: SQL (Structured Query Language) (sql)
每当你向 posts 表中插入一行时,如果没有为 created_at
列指定值,数据库系统将在该列中使用当前日期和时间,如下所示
INSERT INTO posts(id,title)
VALUES(1,'SQL CURRENT_TIMESTAMP test');
Code language: SQL (Structured Query Language) (sql)
让我们检查 posts
表的内容
SELECT * FROM posts;
Code language: SQL (Structured Query Language) (sql)
以下显示了输出

在本教程中,你已经了解如何使用 SQL CURRENT_TIMESTAMP
函数来获取数据库服务器的当前日期和时间。
本教程是否有帮助?