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 函式來獲取資料庫伺服器的當前日期和時間。

本教程是否有幫助?
© .