SQL CURRENT_TIMESTAMP

摘要:在本教程中,您将学习如何使用 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 通常用于为表的 DATETIMETIMESTAMP 列设置默认值。

例如,以下语句创建了一个新表,该表有一个 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 example

在本教程中,您学习了如何使用 SQL CURRENT_TIMESTAMP 函数来获取数据库服务器的当前日期和时间。

本教程是否有帮助?
© .