摘要:在本教學中,您將學習如何使用 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
函數來取得資料庫伺服器目前的日期與時間。
這個教學對您有幫助嗎?